灵活掌握asp.net中gridview控件的多种使用方法(上)
灵活使用asp.net中gridview控件的方法有很多种,本文内容很富,希望大家都能有所收获。
1.gridview无代码分页排序:
效果图:
小提示:
1.allowsorting设为true,aspx代码中是allowsorting="true";
2.默认1页10条,如果要修改每页条数,修改pagesize即可,在aspx代码中是pagesize="12"。
3.默认的是单向排序的,右击gridview弹出“属性”,选择allowsorting为true即可。
2.gridview选中,编辑,取消,删除:
效果图:
后台代码:
你可以使用sqlhelper,本文没用。代码如下:
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" cellpadding="4" forecolor="#333333" gridlines="none" onrowdeleting="gridview1_rowdeleting" onrowediting="gridview1_rowediting" onrowupdating="gridview1_rowupdating" 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" /> </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" /> </asp:gridview>
3.gridview正反双向排序:
效果图:点姓名各2次的排序,点其他也一样可以。
后台代码:
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" cellpadding="3" font-size="9pt" onsorting="gridview1_sorting" 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:boundfield datafield="员工性别" headertext="性别" sortexpression="员工性别"/> <asp:boundfield datafield="家庭住址" headertext="家庭住址" sortexpression="家庭住址"/> </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" /> </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" 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='<%# ddlbind()%>' datavaluefield="员工性别" datatextfield="员工性别"> </asp:dropdownlist> </itemtemplate> </asp:templatefield> <asp:boundfield datafield="家庭住址" headertext="家庭住址" sortexpression="家庭住址"/> </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" /> </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" 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" /> </itemtemplate> </asp:templatefield> <asp:boundfield datafield="身份证号码" headertext="用户id" sortexpression="身份证号码" /> <asp:boundfield datafield="姓名" headertext="用户姓名" sortexpression="姓名"/> <asp:boundfield datafield="家庭住址" headertext="家庭住址" sortexpression="家庭住址"/> </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" /> </asp:gridview> <asp:checkbox id="checkbox2" runat="server" font-size="9pt" oncheckedchanged="checkbox2_checkedchanged" text="全选" /> <asp:button id="button1" runat="server" font-size="9pt" text="取消" onclick="button1_click" /> <asp:button id="button2" runat="server" font-size="9pt" text="删除" onclick="button2_click" />
6.鼠标移到gridview某一行时改变该行的背景色方法一:
效果图:
做法:
双击gridview的onrowdatabound事件;
在后台的gridview1_rowdatabound()方法添加代码,最后代码如下所示:
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e) { int i; //执行循环,保证每条数据都可以更新 for (i = 0; i < gridview1.rows.count; i++) { //首先判断是否是数据行 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"); } } }
前台代码:
<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>实现鼠标划过改变gridview的行背景色 清清月儿http://blog.csdn.net/21aspnet </title> </head> <body> <form id="form1" runat="server"> <div> <asp:gridview id="gridview1" runat="server" datakeynames="身份证号码" datasourceid="sqldatasource1" allowsorting="true" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" font-size="12px" 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="邮政编码" /> </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" /> </asp:gridview> <asp:sqldatasource id="sqldatasource1" runat="server" connectionstring="<%$ connectionstrings:北风贸易connectionstring1 %>" selectcommand="select top 5 [身份证号码], [姓名], [员工性别], [家庭住址], [邮政编码] from [飞狐工作室]" datasourcemode="datareader"></asp:sqldatasource> </div> </form> </body> </html>
7.鼠标移到gridview某一行时改变该行的背景色方法二:
效果图:
做法:和上面的一样就是代码不同
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e) { //int i; ////执行循环,保证每条数据都可以更新 //for (i = 0; i < gridview1.rows.count; i++) //{ // //首先判断是否是数据行 // 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"); // } //} //如果是绑定数据行 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.rowtype == datacontrolrowtype.datarow) { ////鼠标经过时,行背景色变 //e.row.attributes.add("onmouseover", "this.style.backgroundcolor='#e6f5fa'"); ////鼠标移出时,行背景色变 //e.row.attributes.add("onmouseout", "this.style.backgroundcolor='#ffffff'"); ////当有编辑列时,避免出错,要加的rowstate判断 //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 + "/"吗?')"); //} } if (e.row.rowindex != -1) { int id = e.row.rowindex + 1; e.row.cells[0].text = id.tostring(); } }
注意这时最好把前台的第一列的表头该为“编号”,因为以前的第一列被“吃掉”了。
<asp:gridview id="gridview1" runat="server" cellpadding="3" onrowdeleting="gridview1_rowdeleting" onrowediting="gridview1_rowediting" onrowupdating="gridview1_rowupdating" onrowcancelingedit="gridview1_rowcancelingedit" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" font-size="12px" onrowdatabound="gridview1_rowdatabound"> <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" /> </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" /> </asp:gridview>
10.gridview实现自定义时间货币等字符串格式:
效果图:
图1-未格式化前
图2-格式化后
解决方法:
在asp.net 2.0中,如果要在绑定列中显示比如日期格式等,如果用下面的方法是显示不了的
<asp :boundfield datafield="creationdate" dataformatstring="{0:m-dd-yyyy}" headertext="creationdate" />
主要是由于htmlencode属性默认设置为true,已防止xss攻击,安全起见而用的,所以,可以有以下两种方法解决
第一种:
<asp :gridview id="gridview1" runat="server"> <columns> <asp :boundfield datafield="creationdate" dataformatstring="{0:m-dd-yyyy}" htmlencode="false" headertext="creationdate" /> </columns> </asp>
将htmlencode设置为false即可
另外的解决方法为,使用模版列
<asp :gridview id="gridview3" runat="server" > <columns> <asp :templatefield headertext="creationdate" > <edititemtemplate> <asp :label id="label1" runat="server" text='<%# eval_r("creationdate", "{0:m-dd-yyyy}") %>'> </asp> </edititemtemplate> <itemtemplate> <asp :label id="label1" runat="server" text='<%# bind("creationdate", "{0:m-dd-yyyy}") %>'> </asp> </itemtemplate> </asp> </columns> </asp>
前台代码:
<asp:gridview id="gridview1" runat="server" datakeynames="身份证号码" datasourceid="sqldatasource1" allowsorting="true" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" font-size="12px" 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="起薪" /> </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" /> </asp:gridview> <asp:sqldatasource id="sqldatasource1" runat="server" connectionstring="<%$ connectionstrings:北风贸易connectionstring1 %>" selectcommand="select top 5 [出生日期], [起薪], [身份证号码], [姓名], [家庭住址], [邮政编码] from [飞狐工作室]" datasourcemode="datareader"></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
为大家附3个精彩的专题:
以上就是asp.net中gridview控件的多种使用方法的第一篇,内容很丰富,之后还有终结篇,希望大家不要错过。