Asp.net中GridView使用详解
lgridview无代码分页排序
lgridview选中,编辑,取消,删除
lgridview正反双向排序
lgridview和下拉菜单dropdownlist结合
lgridview和checkbox结合
l鼠标移到gridview某一行时改变该行的背景色方法一
l鼠标移到gridview某一行时改变该行的背景色方法二
lgridview实现删除时弹出确认对话框
lgridview实现自动编号
lgridview实现自定义时间货币等字符串格式
lgridview实现用“...”代替超长字符串
lgridview一般换行与强制换行
lgridview显示隐藏某一列
lgridview弹出新页面/弹出新窗口
lgridview固定表头(不用javascript只用css,2行代码,很好用)
lgridview合并表头多重表头无错完美版(以合并3列3行举例)
lgridview突出显示某一单元格(例如金额低于多少,分数不及格等)
lgridview加入自动求和求平均值小计
lgridview数据导入excel/excel数据读入gridview
1.gridview简单代码分页排序:
1.allowsorting设为true,x代码中是allowsorting="true";
2.默认1页10条,如果要修改每页条数,修改pagesize即可,在aspx代码中是pagesize="12"。
3.默认的是单向排序的,右击gridview弹出“属性”,选择allowsorting为true即可。
4.添加代码:
protected void gridview1_pageindexchanging(object sender, gridviewpageeventargs e) { gridview1.pageindex = e.newpageindex; bind(); }
2.gridview选中,编辑,取消,删除:
后台代码:
using system; using system.data; using system.configuration; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.data.sqlclient; public partial class _default : system.web.ui.page { sqlconnection sqlcon; sqlcommand sqlcom; string strcon = "data source=(local);database=数据库名;uid=帐号;pwd=密码"; protected void page_load(object sender, eventargs e) { if (!ispostback) { bind(); } } protected void gridview1_rowediting(object sender, gridviewediteventargs e) { gridview1.editindex = e.neweditindex; bind(); } //删除 protected void gridview1_rowdeleting(object sender, gridviewdeleteeventargs e) { string sqlstr = "delete from 表 where id='" + gridview1.datakeys[e.rowindex].value.tostring() + "'"; sqlcon = new sqlconnection(strcon); sqlcom = new sqlcommand(sqlstr,sqlcon); sqlcon.open(); sqlcom.executenonquery(); sqlcon.close(); bind(); } //更新 protected void gridview1_rowupdating(object sender, gridviewupdateeventargs e) { sqlcon = new sqlconnection(strcon); string sqlstr = "update 表 set 字段1='" + ((textbox)(gridview1.rows[e.rowindex].cells[1].controls[0])).text.tostring().trim() + "',字段2='" + ((textbox)(gridview1.rows[e.rowindex].cells[2].controls[0])).text.tostring().trim() + "',字段3='" + ((textbox)(gridview1.rows[e.rowindex].cells[3].controls[0])).text.tostring().trim() + "' where id='" + gridview1.datakeys[e.rowindex].value.tostring() + "'"; sqlcom=new sqlcommand(sqlstr,sqlcon); sqlcon.open(); sqlcom.executenonquery(); sqlcon.close(); gridview1.editindex = -1; bind(); } //取消 protected void gridview1_rowcancelingedit(object sender, gridviewcancelediteventargs e) { gridview1.editindex = -1; bind(); } //绑定 public void bind() { string sqlstr = "select * from 表"; sqlcon = new sqlconnection(strcon); sqldataadapter myda = new sqldataadapter(sqlstr, sqlcon); dataset myds = new dataset(); sqlcon.open(); myda.fill(myds, "表"); gridview1.datasource = myds; gridview1.datakeynames = new string[] { "id" };//主键 gridview1.databind(); sqlcon.close(); } }
前台主要代码:
<asp:gridview id="gridview1" runat="server" autogeneratecolumns="false" cellpadding="4" forecolor="#333333" gridlines="none" data-cke-pa-onrowdeleting="gridview1_rowdeleting" data-cke-pa-onrowediting="gridview1_rowediting" data-cke-pa-onrowupdating="gridview1_rowupdating" data-cke-pa-onrowcancelingedit="gridview1_rowcancelingedit"> <footerstyle backcolor="#990000" font-bold="true" forecolor="white"> <columns> <asp:boundfield datafield="身份证号码" headertext="用户id" readonly="true"> <asp:boundfield datafield="姓名" headertext="用户姓名"> <asp:boundfield datafield="员工性别" headertext="性别"> <asp:boundfield datafield="家庭住址" headertext="家庭住址"> <asp:commandfield headertext="选择" showselectbutton="true"> <asp:commandfield headertext="编辑" showeditbutton="true"> <asp:commandfield headertext="删除" showdeletebutton="true"> </asp:commandfield></asp:commandfield></asp:commandfield></asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview>
3.gridview正反双向排序:
后台代码:
using system; using system.data; using system.configuration; using system.collections; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.data.sqlclient; public partial class default3 : system.web.ui.page { sqlconnection sqlcon; string strcon = "data source=(local);database=北风贸易;uid=sa;pwd="; protected void page_load(object sender, eventargs e) { if (!ispostback) { viewstate["sortorder"] = "身份证号码"; viewstate["orderdire"] = "asc"; bind(); } } protected void gridview1_sorting(object sender, gridviewsorteventargs e) { string spage = e.sortexpression; if (viewstate["sortorder"].tostring() == spage) { if (viewstate["orderdire"].tostring() == "desc") viewstate["orderdire"] = "asc"; else viewstate["orderdire"] = "desc"; } else { viewstate["sortorder"] = e.sortexpression; } bind(); } public void bind() { string sqlstr = "select top 5 * from 飞狐工作室"; sqlcon = new sqlconnection(strcon); sqldataadapter myda = new sqldataadapter(sqlstr, sqlcon); dataset myds = new dataset(); sqlcon.open(); myda.fill(myds, "飞狐工作室"); dataview view = myds.tables["飞狐工作室"].defaultview; string sort = (string)viewstate["sortorder"] + " " + (string)viewstate["orderdire"]; view.sort = sort; gridview1.datasource = view; gridview1.databind(); sqlcon.close(); } }
前台主要代码:
<asp:gridview id="gridview1" runat="server" allowsorting="true" autogeneratecolumns="false" cellpadding="3" font-size="9pt" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" data-cke-pa-onsorting="gridview1_sorting"> <footerstyle backcolor="white" forecolor="#000066"> <columns> <asp:boundfield datafield="身份证号码" headertext="用户id" sortexpression="身份证号码"> <asp:boundfield datafield="姓名" headertext="用户姓名" sortexpression="姓名"> <asp:boundfield datafield="员工性别" headertext="性别" sortexpression="员工性别"> <asp:boundfield datafield="家庭住址" headertext="家庭住址" sortexpression="家庭住址"> </asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview>
4.gridview和下拉菜单dropdownlist结合:
后台代码:
using system; using system.data; using system.configuration; using system.collections; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.data.sqlclient; public partial class default4 : system.web.ui.page { sqlconnection sqlcon; string strcon = "data source=(local);database=北风贸易;uid=sa;pwd=sa"; protected void page_load(object sender, eventargs e) { dropdownlist ddl; if (!ispostback) { string sqlstr = "select top 5 * from 飞狐工作室"; sqlcon = new sqlconnection(strcon); sqldataadapter myda = new sqldataadapter(sqlstr, sqlcon); dataset myds = new dataset(); sqlcon.open(); myda.fill(myds, "飞狐工作室"); gridview1.datasource = myds; gridview1.databind(); for (int i = 0; i <= gridview1.rows.count - 1; i++) { datarowview mydrv = myds.tables["飞狐工作室"].defaultview[i]; if (convert.tostring(mydrv["员工性别"]).trim() == "true") { ddl = (dropdownlist)gridview1.rows[i].findcontrol("dropdownlist1"); ddl.selectedindex = 0; } if (convert.tostring(mydrv["员工性别"]).trim() == "false") { ddl = (dropdownlist)gridview1.rows[i].findcontrol("dropdownlist1"); ddl.selectedindex = 1; } } sqlcon.close(); } } public sqldatareader ddlbind() { string sqlstr = "select distinct 员工性别 from 飞狐工作室"; sqlcon = new sqlconnection(strcon); sqlcommand sqlcom = new sqlcommand(sqlstr, sqlcon); sqlcon.open(); return sqlcom.executereader(); }
前台主要代码:
<asp:gridview id="gridview1" runat="server" allowsorting="true" autogeneratecolumns="false" cellpadding="3" font-size="9pt" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px"> <footerstyle backcolor="white" forecolor="#000066"> <columns> <asp:boundfield datafield="身份证号码" headertext="用户id" sortexpression="身份证号码"> <asp:boundfield datafield="姓名" headertext="用户姓名" sortexpression="姓名"> <asp:templatefield headertext="员工性别"> <itemtemplate> <asp:dropdownlist id="dropdownlist1" runat="server" datasource="'<%#">' datavaluefield="员工性别" datatextfield="员工性别"> </asp:dropdownlist> </itemtemplate> </asp:templatefield> <asp:boundfield datafield="家庭住址" headertext="家庭住址" sortexpression="家庭住址"> </asp:boundfield></asp:boundfield></asp:boundfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview>
5.gridview和checkbox结合:
后台代码:
using system; using system.data; using system.configuration; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.data.sqlclient; public partial class default5 : system.web.ui.page { sqlconnection sqlcon; string strcon = "data source=(local);database=北风贸易;uid=sa;pwd=sa"; protected void page_load(object sender, eventargs e) { if (!ispostback) { bind(); } } protected void checkbox2_checkedchanged(object sender, eventargs e) { for (int i = 0; i <= gridview1.rows.count - 1; i++) { checkbox cbox = (checkbox)gridview1.rows[i].findcontrol("checkbox1"); if (checkbox2.checked == true) { cbox.checked = true; } else { cbox.checked = false; } } } protected void button2_click(object sender, eventargs e) { sqlcon = new sqlconnection(strcon); sqlcommand sqlcom; for (int i = 0; i <= gridview1.rows.count - 1; i++) { checkbox cbox = (checkbox)gridview1.rows[i].findcontrol("checkbox1"); if (cbox.checked == true) { string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + gridview1.datakeys[i].value + "'"; sqlcom = new sqlcommand(sqlstr, sqlcon); sqlcon.open(); sqlcom.executenonquery(); sqlcon.close(); } } bind(); } protected void button1_click(object sender, eventargs e) { checkbox2.checked = false; for (int i = 0; i <= gridview1.rows.count - 1; i++) { checkbox cbox = (checkbox)gridview1.rows[i].findcontrol("checkbox1"); cbox.checked = false; } } public void bind() { string sqlstr = "select top 5 * from 飞狐工作室"; sqlcon = new sqlconnection(strcon); sqldataadapter myda = new sqldataadapter(sqlstr, sqlcon); dataset myds = new dataset(); sqlcon.open(); myda.fill(myds, "tb_member"); gridview1.datasource = myds; gridview1.datakeynames = new string[] { "身份证号码" }; gridview1.databind(); sqlcon.close(); } }前台主要代码:
<asp:gridview id="gridview1" runat="server" allowsorting="true" autogeneratecolumns="false" cellpadding="3" font-size="9pt" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px"> <footerstyle backcolor="white" forecolor="#000066"> <columns> <asp:templatefield> <itemtemplate> <asp:checkbox id="checkbox1" runat="server"> </asp:checkbox></itemtemplate> </asp:templatefield> <asp:boundfield datafield="身份证号码" headertext="用户id" sortexpression="身份证号码"> <asp:boundfield datafield="姓名" headertext="用户姓名" sortexpression="姓名"> <asp:boundfield datafield="家庭住址" headertext="家庭住址" sortexpression="家庭住址"> </asp:boundfield></asp:boundfield></asp:boundfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview> <asp:checkbox id="checkbox2" runat="server" autopostback="true" font-size="9pt" text="全选" data-cke-pa-oncheckedchanged="checkbox2_checkedchanged"> <asp:button id="button1" runat="server" font-size="9pt" text="取消" data-cke-pa-onclick="button1_click"> <asp:button id="button2" runat="server" font-size="9pt" text="删除" data-cke-pa-onclick="button2_click"></asp:button></asp:button></asp:checkbox>
6.鼠标移到gridview某一行时改变该行的背景色方法一:
做法:
双击gridview的onrowdatabound事件;
在后台的gridview1_rowdatabound()方法添加代码,最后代码如下所示:
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e) { //首先判断是否是数据行 if (e.row.rowtype == datacontrolrowtype.datarow) { //当鼠标停留时更改背景色 e.row.attributes.add("onmouseover", "c=this.style.backgroundcolor;this.style.backgroundcolor='#00a9ff'"); //当鼠标移开时还原背景色 e.row.attributes.add("onmouseout", "this.style.backgroundcolor=c"); } }
前台代码:
<form id="form1" runat="server"> <p><asp:gridview allowsorting="true" autogeneratecolumns="false" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" datakeynames="身份证号码" datasourceid="sqldatasource1" font-size="12px" id="gridview1" onrowdatabound="gridview1_rowdatabound" runat="server"> <columns> <asp:boundfield datafield="身份证号码" headertext="身份证号码" readonly="true" sortexpression="身份证号码"> <asp:boundfield datafield="姓名" headertext="姓名" sortexpression="姓名"> <asp:boundfield datafield="家庭住址" headertext="家庭住址" sortexpression="家庭住址"> <asp:boundfield datafield="邮政编码" headertext="邮政编码" sortexpression="邮政编码"> </asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></columns> <footerstyle backcolor="white" forecolor="#000066"> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview> <asp:sqldatasource connectionstring="<%$ connectionstrings:北风贸易connectionstring1 %>" datasourcemode="datareader" id="sqldatasource1" runat="server" selectcommand="select top 5 [身份证号码], [姓名], [员工性别], [家庭住址], [邮政编码] from [飞狐工作室]"></asp:sqldatasource></p> </form>
7.鼠标移到gridview某一行时改变该行的背景色方法二:
做法:和上面的一样就是代码不同
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e) { //如果是绑定数据行 if (e.row.rowtype == datacontrolrowtype.datarow) { //鼠标经过时,行背景色变 e.row.attributes.add("onmouseover", "this.style.backgroundcolor='#e6f5fa'"); //鼠标移出时,行背景色变 e.row.attributes.add("onmouseout", "this.style.backgroundcolor='#ffffff'"); } }
8.gridview实现删除时弹出确认对话框:
实现方法:
双击gridview的onrowdatabound事件;
在后台的gridview1_rowdatabound()方法添加代码,最后代码如下所示:
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e) { //如果是绑定数据行 if (e.row.rowtype == datacontrolrowtype.datarow) { if (e.row.rowstate == datacontrolrowstate.normal || e.row.rowstate == datacontrolrowstate.alternate) { ((linkbutton)e.row.cells[6].controls[0]).attributes.add("onclick", "javascript:return confirm('你确认要删除:/"" + e.row.cells[1].text + "/"吗?')"); } } }
9.gridview实现自动编号:
实现方法:
双击gridview的onrowdatabound事件;
在后台的gridview1_rowdatabound()方法添加代码,最后代码如下所示:
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e) { if (e.row.rowindex != -1) { int id = e.row.rowindex + 1; e.row.cells[0].text = id.tostring(); } }
注意这时最好把前台的第一列的表头该为“编号”,因为以前的第一列被“吃掉”了。
<asp:gridview autogeneratecolumns="false" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" font-size="12px" id="gridview1" runat="server" data-cke-pa-onrowcancelingedit="gridview1_rowcancelingedit" data-cke-pa-onrowdatabound="gridview1_rowdatabound" data-cke-pa-onrowdeleting="gridview1_rowdeleting" data-cke-pa-onrowediting="gridview1_rowediting" data-cke-pa-onrowupdating="gridview1_rowupdating"> <footerstyle backcolor="white" forecolor="#000066"> <columns> <asp:boundfield datafield="身份证号码" headertext="编号" readonly="true"> <asp:boundfield datafield="姓名" headertext="用户姓名"> <asp:boundfield datafield="员工性别" headertext="性别"> <asp:boundfield datafield="家庭住址" headertext="家庭住址"> <asp:commandfield headertext="选择" showselectbutton="true"> <asp:commandfield headertext="编辑" showeditbutton="true"> <asp:commandfield headertext="删除" showdeletebutton="true"> </asp:commandfield></asp:commandfield></asp:commandfield></asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview>
10.gridview实现自定义时间货币等字符串格式:
解决方法:
在asp.net 2.0中,如果要在绑定列中显示比如日期格式等,如果用下面的方法是显示不了的
主要是由于htmlencode属性默认设置为true,已防止xss攻击,安全起见而用的,所以,可以有以下两种方法解决
1、
<asp :gridview="" id="gridview1" runat="server"> <columns> <asp :boundfield="" datafield="creationdate" dataformatstring="{0:m-dd-yyyy}" headertext="creationdate" htmlencode="false"> </asp></columns> </asp>
将htmlencode设置为false即可
另外的解决方法为,使用模版列
<asp :gridview="" id="gridview3" runat="server"> <columns> <asp :templatefield="" headertext="creationdate"> <edititemtemplate> <asp :label="" id="label1" runat="server" text="'<%#">'> </asp> </edititemtemplate> <itemtemplate> <asp :label="" id="label1" runat="server" text="’<%#">'> </asp> </itemtemplate> </asp> </columns> </asp>
前台代码:
<asp:gridview allowsorting="true" autogeneratecolumns="false" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" datakeynames="身份证号码" datasourceid="sqldatasource1" font-size="12px" id="gridview1" runat="server" data-cke-pa-onrowdatabound="gridview1_rowdatabound"> <columns> <asp:boundfield datafield="身份证号码" headertext="身份证号码" readonly="true" sortexpression="身份证号码"> <asp:boundfield datafield="姓名" headertext="姓名" sortexpression="姓名"> <asp:boundfield datafield="邮政编码" headertext="邮政编码" sortexpression="邮政编码"> <asp:boundfield datafield="出生日期" headertext="出生日期" sortexpression="出生日期"> <asp:boundfield datafield="起薪" headertext="起薪" sortexpression="起薪"> </asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></columns> <footerstyle backcolor="white" forecolor="#000066"> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview> <asp:sqldatasource connectionstring="<%$ connectionstrings:北风贸易connectionstring1 %>" datasourcemode="datareader" id="sqldatasource1" runat="server" selectcommand="select top 5 [出生日期], [起薪], [身份证号码], [姓名], [家庭住址], [邮政编码] from [飞狐工作室]"></asp:sqldatasource>
附录-常用格式化公式:
{0:c}货币;
{0:d4}由0填充的4个字符宽的字段中显示整数;
{0:000.0}四舍五入小数点保留第几位有效数字;
{0:n2}小数点保留2位有效数字;{0:n2}%小数点保留2位有效数字加百分号;
{0:d}长日期;{0:d}短日期;{0:yy-mm-dd}例如07-3-25;;{0:yyyy-mm-dd}例如2007-3-25
11.gridview实现用“...”代替超长字符串:
解决方法:数据绑定后过滤每一行即可
for (int i = 0; i <= gridview1.rows.count - 1; i++) { datarowview mydrv; string gintro; if (gridview1.pageindex == 0) { mydrv = myds.tables["飞狐工作室"].defaultview[i];//表名 gintro = convert.tostring(mydrv["家庭住址"]);//所要处理的字段 gridview1.rows[i].cells[3].text = substr(gintro, 2); } else { mydrv = myds.tables["飞狐工作室"].defaultview[i + (5 * gridview1.pageindex)]; gintro = convert.tostring(mydrv["家庭住址"]); gridview1.rows[i].cells[3].text = substr(gintro, 2); } }
调用的方法:
public string substr(string sstring, int nleng) { if (sstring.length <= nleng) { return sstring; } string snewstr = sstring.substring(0, nleng); snewstr = snewstr + "..."; return snewstr; }
12.gridview一般换行与强制换行:
首先设置
protected void page_load(object sender, eventargs e) { //正常换行 gridview1.attributes.add("style", "word-break:keep-all;word-wrap:normal"); //下面这行是自动换行 gridview1.attributes.add("style", "word-break:break-all;word-wrap:break-word"); if (!ispostback) { bind();//调用数据绑定即可 } }
总之:善用css的word-break:break-all;word-wrap:break-word属性即可,这个属性是通用的对于顽固的南换行问题都可以解决,不局限于gridview。
13.gridview显示隐藏某一列:
解决方案:
public void bind() { string sqlstr = "select top 5 * from 飞狐工作室"; sqlcon = new sqlconnection(strcon); sqldataadapter myda = new sqldataadapter(sqlstr, sqlcon); dataset myds = new dataset(); sqlcon.open(); myda.fill(myds, "飞狐工作室"); gridview1.datasource = myds; gridview1.datakeynames = new string[] { "身份证号码" }; gridview1.databind(); sqlcon.close(); gridview1.columns[3].visible = false;//一开始隐藏 checkbox1.checked = false;//如果不这样后面的代码会把他true }
双击checkbox1,在checkedchanged方法里写上代码,最后代码如下:
protected void checkbox1_checkedchanged(object sender, eventargs e) { gridview1.columns[3].visible=! gridview1.columns[3].visible; response.write("gridview1的第4列现在的显示隐藏状态是:"+gridview1.columns[3].visible.tostring()); }
注意:checkbox1的autopostback要true!
后台全部代码如下:
using system; using system.data; using system.configuration; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.data.sqlclient; public partial class _default : system.web.ui.page { sqlconnection sqlcon; sqlcommand sqlcom; string strcon = "data source=(local);database=北风贸易;uid=sa;pwd=sa"; protected void page_load(object sender, eventargs e) { if (!ispostback) { viewstate["sortorder"] = "身份证号码"; viewstate["orderdire"] = "asc"; bind(); } } protected void gridview1_rowediting(object sender, gridviewediteventargs e) { gridview1.editindex = e.neweditindex; bind(); } protected void gridview1_rowdeleting(object sender, gridviewdeleteeventargs e) { string sqlstr = "delete from 飞狐工作室 where 身份证号码='" + gridview1.datakeys[e.rowindex].value.tostring() + "'"; sqlcon = new sqlconnection(strcon); sqlcom = new sqlcommand(sqlstr,sqlcon); sqlcon.open(); sqlcom.executenonquery(); sqlcon.close(); bind(); } protected void gridview1_rowupdating(object sender, gridviewupdateeventargs e) { sqlcon = new sqlconnection(strcon); string sqlstr = "update 飞狐工作室 set 姓名='" + ((textbox)(gridview1.rows[e.rowindex].cells[1].controls[0])).text.tostring().trim() + "',家庭住址='" + ((textbox)(gridview1.rows[e.rowindex].cells[3].controls[0])).text.tostring().trim() + "' where 身份证号码='" + gridview1.datakeys[e.rowindex].value.tostring() + "'"; sqlcom=new sqlcommand(sqlstr,sqlcon); sqlcon.open(); sqlcom.executenonquery(); sqlcon.close(); gridview1.editindex = -1; bind(); } protected void gridview1_rowcancelingedit(object sender, gridviewcancelediteventargs e) { gridview1.editindex = -1; bind(); } public void bind() { string sqlstr = "select top 5 * from 飞狐工作室"; sqlcon = new sqlconnection(strcon); sqldataadapter myda = new sqldataadapter(sqlstr, sqlcon); dataset myds = new dataset(); sqlcon.open(); myda.fill(myds, "飞狐工作室"); gridview1.datasource = myds; gridview1.datakeynames = new string[] { "身份证号码" }; gridview1.databind(); sqlcon.close(); gridview1.columns[3].visible = false; checkbox1.checked = false; } protected void checkbox1_checkedchanged(object sender, eventargs e) { gridview1.columns[3].visible=! gridview1.columns[3].visible; response.write("gridview1的第4列现在的显示隐藏状态是:"+gridview1.columns[3].visible.tostring()); } }前台代码:
<form id="form1" runat="server"> <p><asp:gridview autogeneratecolumns="false" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" font-size="12px" id="gridview1" onrowcancelingedit="gridview1_rowcancelingedit" onrowdeleting="gridview1_rowdeleting" onrowediting="gridview1_rowediting" onrowupdating="gridview1_rowupdating" runat="server"> <footerstyle backcolor="white" forecolor="#000066"> <columns> <asp:boundfield datafield="身份证号码" headertext="编号" readonly="true"> <asp:boundfield datafield="姓名" headertext="用户姓名"> <asp:boundfield datafield="邮政编码" headertext="邮政编码" sortexpression="邮政编码"> <asp:boundfield datafield="家庭住址" headertext="家庭住址"> <asp:commandfield headertext="选择" showselectbutton="true"> <asp:commandfield headertext="编辑" showeditbutton="true"> <asp:commandfield headertext="删除" showdeletebutton="true"> </asp:commandfield></asp:commandfield></asp:commandfield></asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview> <asp:checkbox autopostback="true" font-size="12px" id="checkbox1" oncheckedchanged="checkbox1_checkedchanged" runat="server" text="显示隐藏家庭住址"></asp:checkbox></p> </form>
14.gridview弹出新页面:
<asp:gridview autogeneratecolumns="false" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" font-size="12px" id="gridview1" runat="server" data-cke-pa-onrowcancelingedit="gridview1_rowcancelingedit" data-cke-pa-onrowdeleting="gridview1_rowdeleting" data-cke-pa-onrowediting="gridview1_rowediting" data-cke-pa-onrowupdating="gridview1_rowupdating"> <footerstyle backcolor="white" forecolor="#000066"> <columns> <asp:boundfield datafield="身份证号码" headertext="编号" readonly="true"> <asp:boundfield datafield="邮政编码" headertext="邮政编码" sortexpression="邮政编码"> <asp:boundfield datafield="家庭住址" headertext="家庭住址"> <asp:hyperlinkfield datanavigateurlfields="姓名" datanavigateurlformatstring="default6.aspx?goodsid={0}" datatextfield="姓名" headertext="姓名" navigateurl="~/default6.aspx" target="mainframe" text="姓名"> </asp:hyperlinkfield> <asp:commandfield headertext="选择" showselectbutton="true"> <asp:commandfield headertext="编辑" showeditbutton="true"> <asp:commandfield headertext="删除" showdeletebutton="true"> </asp:commandfield></asp:commandfield></asp:commandfield></asp:boundfield></asp:boundfield></asp:boundfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview>
datanavigateurlfields是链接的字段名,datanavigateurlformatstring是路径。
15.gridview固定表头(不用javascript只用css!,很好用):
代码:
<style type="text/css"> .freezing { position:relative ; table-layout:fixed; top:expression(this.offsetparent.scrolltop); z-index: 10; } .freezing th{text-overflow:ellipsis;overflow:hidden;white-space: nowrap;padding:2px;}</style> <form id="form1" runat="server"> <p id="dvbody" style="overflow-y: scroll; height: 200px;width:300px"><asp:gridview autogeneratecolumns="false" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" font-size="12px" id="gridview1" onrowcancelingedit="gridview1_rowcancelingedit" onrowcreated="gridview1_rowcreated" onrowdeleting="gridview1_rowdeleting" onrowediting="gridview1_rowediting" onrowupdating="gridview1_rowupdating" runat="server"> <footerstyle backcolor="white" forecolor="#000066"> <columns> <asp:boundfield datafield="身份证号码" headertext="编号" readonly="true"> <asp:boundfield datafield="邮政编码" headertext="邮政编码" sortexpression="邮政编码"> <asp:boundfield datafield="家庭住址" headertext="家庭住址"> <asp:boundfield datafield="姓名" headertext="姓名"> </asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" cssclass="ms-formlabel datagridfixedheader" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" cssclass="freezing" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview></p> </form>
用法:css设如上的样式,headerstyle加cssclass="freezing,套住gridview的div设置高度宽度
16.gridview合并表头多重表头无错完美版(以合并3列3行举例)
后台代码:
protected void gridview1_rowcreated(object sender, gridviewroweventargs e) { switch (e.row.rowtype) { case datacontrolrowtype.header: //第一行表头 tablecellcollection tcheader = e.row.cells; tcheader.clear(); tcheader.add(new tableheadercell()); tcheader[0].attributes.add("rowspan", "3"); //跨row tcheader[0].attributes.add("bgcolor", "white"); tcheader[0].text = ""; tcheader.add(new tableheadercell()); //tcheader[1].attributes.add("bgcolor", "red"); tcheader[1].attributes.add("colspan", "6"); //跨column tcheader[1].text = "全部信息"; //第二行表头 tcheader.add(new tableheadercell()); tcheader[2].attributes.add("bgcolor", "darkseagreen"); tcheader[2].text = "身份证号码"; tcheader.add(new tableheadercell()); tcheader[3].attributes.add("bgcolor", "lightsteelblue"); tcheader[3].attributes.add("colspan", "2"); tcheader[3].text = "基本信息"; tcheader.add(new tableheadercell()); tcheader[4].attributes.add("bgcolor", "darkseagreen"); tcheader[4].text = "福利"; tcheader.add(new tableheadercell()); tcheader[5].attributes.add("bgcolor", "lightsteelblue"); tcheader[5].attributes.add("colspan", "2"); tcheader[5].text = "联系方式"; //第三行表头 tcheader.add(new tableheadercell()); tcheader[6].attributes.add("bgcolor", "khaki"); tcheader[6].text = "身份证号码"; tcheader.add(new tableheadercell()); tcheader[7].attributes.add("bgcolor", "khaki"); tcheader[7].text = "姓名"; tcheader.add(new tableheadercell()); tcheader[8].attributes.add("bgcolor", "khaki"); tcheader[8].text = "出生日期"; tcheader.add(new tableheadercell()); tcheader[9].attributes.add("bgcolor", "khaki"); tcheader[9].text = "薪水"; tcheader.add(new tableheadercell()); tcheader[10].attributes.add("bgcolor", "khaki"); tcheader[10].text = "家庭住址"; tcheader.add(new tableheadercell()); tcheader[11].attributes.add("bgcolor", "khaki"); tcheader[11].text = "邮政编码"; break; } } }前台:
17.gridview突出显示某一单元格(例如金额低于多少,分数不及格等)
解决方案:主要是绑定后过滤
gridview1.databind(); for (int i = 0; i <= gridview1.rows.count - 1; i++) { datarowview mydrv = myds.tables["飞狐工作室"].defaultview[i]; string score = convert.tostring(mydrv["起薪"]); if (convert.todouble(score) < 34297.00)//大家这里根据具体情况设置可能toint32等等 { gridview1.rows[i].cells[4].backcolor = system.drawing.color.red; } } sqlcon.close();
全部后台代码:
using system; using system.data; using system.configuration; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.data.sqlclient; using system.drawing; public partial class default7 : system.web.ui.page { sqlconnection sqlcon; sqlcommand sqlcom; string strcon = "data source=(local);database=北风贸易;uid=sa;pwd=sa"; protected void page_load(object sender, eventargs e) { if (!ispostback) { bind(); } } protected void gridview1_rowediting(object sender, gridviewediteventargs e) { gridview1.editindex = e.neweditindex; bind(); } protected void gridview1_rowupdating(object sender, gridviewupdateeventargs e) { sqlcon = new sqlconnection(strcon); string sqlstr = "update 飞狐工作室 set 姓名='" + ((textbox)(gridview1.rows[e.rowindex].cells[1].controls[0])).text.tostring().trim() + "',家庭住址='" + ((textbox)(gridview1.rows[e.rowindex].cells[3].controls[0])).text.tostring().trim() + "' where 身份证号码='" + gridview1.datakeys[e.rowindex].value.tostring() + "'"; sqlcom = new sqlcommand(sqlstr, sqlcon); sqlcon.open(); sqlcom.executenonquery(); sqlcon.close(); gridview1.editindex = -1; bind(); } protected void gridview1_rowcancelingedit(object sender, gridviewcancelediteventargs e) { gridview1.editindex = -1; bind(); } public void bind() { string sqlstr = "select top 10 * from 飞狐工作室"; sqlcon = new sqlconnection(strcon); sqldataadapter myda = new sqldataadapter(sqlstr, sqlcon); dataset myds = new dataset(); sqlcon.open(); myda.fill(myds, "飞狐工作室"); gridview1.datasource = myds; gridview1.datakeynames = new string[] { "身份证号码" }; gridview1.databind(); for (int i = 0; i <= gridview1.rows.count - 1; i++) { datarowview mydrv = myds.tables["飞狐工作室"].defaultview[i]; string score = convert.tostring(mydrv["起薪"]); if (convert.todouble(score) < 34297.00)//大家这里根据具体情况设置可能toint32等等 { gridview1.rows[i].cells[4].backcolor = system.drawing.color.red; } } sqlcon.close(); } }
前台代码:
<form id="form1" runat="server"> <p><asp:gridview autogeneratecolumns="false" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" font-size="12px" id="gridview1" onrowcancelingedit="gridview1_rowcancelingedit" onrowediting="gridview1_rowediting" onrowupdating="gridview1_rowupdating" runat="server"> <footerstyle backcolor="white" forecolor="#000066"> <columns> <asp:commandfield headertext="编辑" showeditbutton="true"> <asp:boundfield datafield="身份证号码" headertext="编号" readonly="true"> <asp:boundfield datafield="姓名" headertext="姓名"> <asp:boundfield datafield="出生日期" headertext="邮政编码"> <asp:boundfield datafield="起薪" dataformatstring="{0:c}" headertext="起薪" htmlencode="false"> <asp:boundfield datafield="家庭住址" headertext="家庭住址"> <asp:boundfield datafield="邮政编码" headertext="邮政编码"> </asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></asp:boundfield></asp:commandfield></columns> <rowstyle forecolor="#000066"> <selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white"> <pagerstyle backcolor="white" cssclass="ms-formlabel datagridfixedheader" forecolor="#000066" horizontalalign="left"> <headerstyle backcolor="#006699" font-bold="true" forecolor="white"> </headerstyle></pagerstyle></selectedrowstyle></rowstyle></footerstyle></asp:gridview></p> </form>
18.gridview加入自动求和求平均值小计
解决方案
private double sum = 0;//取指定列的数据和,你要根据具体情况对待可能你要处理的是int protected void gridview1_rowdatabound(object sender, gridviewroweventargs e) { if (e.row.rowindex >= 0) { sum += convert.todouble(e.row.cells[6].text); } else if (e.row.rowtype == datacontrolrowtype.footer) { e.row.cells[5].text = "总薪水为:"; e.row.cells[6].text = sum.tostring(); e.row.cells[3].text = "平均薪水为:"; e.row.cells[4].text = ((int)(sum / gridview1.rows.count)).tostring(); } }
后台全部代码:
using system; using system.data; using system.configuration; using system.web; using system.web.security; using system.web.ui; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.web.ui.htmlcontrols; using system.data.sqlclient; using system.drawing; public partial class default7 : system.web.ui.page { sqlconnection sqlcon; sqlcommand sqlcom; string strcon = "data source=(local);database=北风贸易;uid=sa;pwd=sa"; protected void page_load(object sender, eventargs e) { if (!ispostback) { bind(); } } protected void gridview1_rowediting(object sender, gridviewediteventargs e) { gridview1.editindex = e.neweditindex; bind(); } protected void gridview1_rowupdating(object sender, gridviewupdateeventargs e) { sqlcon = new sqlconnection(strcon); string sqlstr = "update 飞狐工作室 set 姓名='" + ((textbox)(gridview1.rows[e.rowindex].cells[1].controls[0])).text.tostring().trim() + "',家庭住址='" + ((textbox)(gridview1.rows[e.rowindex].cells[3].controls[0])).text.tostring().trim() + "' where 身份证号码='" + gridview1.datakeys[e.rowindex].value.tostring() + "'"; sqlcom = new sqlcommand(sqlstr, sqlcon); sqlcon.open(); sqlcom.executenonquery(); sqlcon.close(); gridview1.editindex = -1; bind();