欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

灵活掌握asp.net中gridview控件的多种使用方法(下)

程序员文章站 2023-12-21 19:59:16
继续上篇文章的学习,在此基础上巩固gridview控件的操作使用,更上一层楼。 11.gridview实现用“...”代替超长字符串: 效果图:  ...

继续上篇文章的学习,在此基础上巩固gridview控件的操作使用,更上一层楼。

11.gridview实现用“...”代替超长字符串:
效果图:

 灵活掌握asp.net中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;
}

后台全部代码:

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();
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);
}
}

sqlcon.close();
}
public string substr(string sstring, int nleng)
{
if (sstring.length <= nleng)
{
return sstring;
}
string snewstr = sstring.substring(0, nleng);
snewstr = snewstr + "...";
return snewstr;
}
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();
}

}
}

12.gridview一般换行与强制换行:

效果图:

 灵活掌握asp.net中gridview控件的多种使用方法(下)

首先设置<asp:boundfield datafield="家庭住址" headertext="家庭住址" itemstyle-width="100" />
gridview里有一列绑定的数据很长,显示的时候在一行里面显示,页面拉得很宽。
原因是连续英文段为一个整体导致的,在rowdatabound中添加上了一句e.row.cells[2].style.add("word-break", "break-all")就可以。

如果要给所有的列增加此属性:

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显示隐藏某一列:
本方案为月儿独创,不同于网上其他方式,我觉得用一个checkbox更人性化,这样可以隐藏不必要的列,让用户自己选择需要出现的列,在处理多列时这是一个很好的解决方案!

效果图:

图1-开始 

灵活掌握asp.net中gridview控件的多种使用方法(下)

图2-点击显示的checkbox后

灵活掌握asp.net中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());
}
}

前台代码:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>gridview显示隐藏列 </title>
</head>
<body style="font-size=12px">
<form id="form1" runat="server">
<div>
<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" >
<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" />
</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="checkbox1" runat="server" font-size="12px"
oncheckedchanged="checkbox1_checkedchanged" text="显示隐藏家庭住址" /></div>
</form>
</body>
</html>

14.gridview弹出新页面/弹出制定大小位置新窗口:

效果图:

灵活掌握asp.net中gridview控件的多种使用方法(下)

方案一:简单的方法,新窗口不固定大小

<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" >
<footerstyle backcolor="white" forecolor="#000066" />
<columns>
<asp:boundfield datafield="身份证号码" headertext="编号" readonly="true" />
<asp:boundfield datafield="邮政编码" headertext="邮政编码" sortexpression="邮政编码" />
<asp:boundfield datafield="家庭住址" headertext="家庭住址" />
<asp:hyperlinkfield headertext="姓名" text="姓名" datanavigateurlfields="姓名" datanavigateurlformatstring="default6.aspx?goodsid={0}" target="mainframe" navigateurl="~/default6.aspx" datatextfield="姓名" >
</asp:hyperlinkfield>
<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>

datanavigateurlfields是链接的字段名,datanavigateurlformatstring是路径。

方案二:精确控制弹出窗口大小位置

<asp:hyperlinkcolumn datanavigateurlfield="employeeid" datanavigateurlformatstring="javascript:varwin=window.open('detail.aspx?id={0}',null,'width=300,height=200');window.close();"
datatextfield="lastname" headertext="lastname"></asp:hyperlinkcolumn>

15.gridview固定表头(不用javascript只用css!,很好用):

效果图:

灵活掌握asp.net中gridview控件的多种使用方法(下)

代码:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>gridview固定表头</title>
<style>
.freezing
{

position:relative ;
table-layout:fixed;
top:expression_r(this.offsetparent.scrolltop);
z-index: 10;
}

.freezing th{text-overflow:ellipsis;overflow:hidden;white-space: nowrap;padding:2px;}
</style>
</head>
<body style="font-size=12px">
<form id="form1" runat="server">
<div style="overflow-y: scroll; height: 200px;width:300px" id="dvbody">
<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" onrowcreated="gridview1_rowcreated" >
<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="姓名" />

</columns>
<rowstyle forecolor="#000066" />
<selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white" />
<pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left" cssclass="ms-formlabel datagridfixedheader"/>
<headerstyle backcolor="#006699" font-bold="true" forecolor="white" cssclass="freezing"/>
</asp:gridview>
</div>

</form>
</body>
</html>

用法:css设如上的样式,headerstyle加cssclass="freezing,套住gridview的div设置高度宽度 <div style="overflow-y: scroll; height: 200px;width:200px" >

16.gridview合并表头多重表头无错完美版(以合并3列3行举例)

效果图:

灵活掌握asp.net中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;
using system.drawing;
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)
{
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();
sqlcon.close();
}

//这里就是解决方案
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 = "全部信息</th></tr><tr>";

//第二行表头
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 = "联系方式</th></tr><tr>";

//第三行表头
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;
}
}
}

前台:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>gridview合并多重表头表头</title>
</head>
<body >
<form id="form1" runat="server">
<div >
<asp:gridview id="gridview1" runat="server" cellpadding="3" onrowediting="gridview1_rowediting"
onrowupdating="gridview1_rowupdating" onrowcancelingedit="gridview1_rowcancelingedit" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" font-size="12px" onrowcreated="gridview1_rowcreated" >
<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="起薪" headertext="起薪" />
<asp:boundfield datafield="家庭住址" headertext="家庭住址" />
<asp:boundfield datafield="邮政编码" headertext="邮政编码" />

</columns>
<rowstyle forecolor="#000066" />
<selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white" />
<pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left" cssclass="ms-formlabel datagridfixedheader"/>
<headerstyle backcolor="#006699" font-bold="true" forecolor="white" />
</asp:gridview>
</div>

</form>
</body>
</html>

17.gridview突出显示某一单元格(例如金额低于多少,分数不及格等)

效果图:

灵活掌握asp.net中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();
}
}

前台代码:

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="head1" runat="server">
<title>gridview突出显示某一单元格 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body >
<form id="form1" runat="server">
<div >
<asp:gridview id="gridview1" runat="server" cellpadding="3" onrowediting="gridview1_rowediting"
onrowupdating="gridview1_rowupdating" onrowcancelingedit="gridview1_rowcancelingedit" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" font-size="12px" >
<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="起薪" headertext="起薪" dataformatstring="{0:c}" htmlencode="false"/>
<asp:boundfield datafield="家庭住址" headertext="家庭住址" />
<asp:boundfield datafield="邮政编码" headertext="邮政编码" />

</columns>
<rowstyle forecolor="#000066" />
<selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white" />
<pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left" cssclass="ms-formlabel datagridfixedheader"/>
<headerstyle backcolor="#006699" font-bold="true" forecolor="white" />
</asp:gridview>
</div>

</form>
</body>
</html>

18.gridview加入自动求和求平均值小计

效果图:

灵活掌握asp.net中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();
}
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();
}
private double sum = 0;//取指定列的数据和
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();

}
}
}

前台:唯一的花头就是设置showfooter="true" ,否则默认表头为隐藏的!

<asp:gridview id="gridview1" runat="server" cellpadding="3" onrowediting="gridview1_rowediting"
onrowupdating="gridview1_rowupdating" onrowcancelingedit="gridview1_rowcancelingedit" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" font-size="12px" onrowdatabound="gridview1_rowdatabound" showfooter="true" >
<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="家庭住址" headertext="家庭住址" />
<asp:boundfield datafield="邮政编码" headertext="邮政编码" />
<asp:boundfield datafield="起薪" headertext="起薪" />

</columns>
<rowstyle forecolor="#000066" />
<selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white" />
<pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left" cssclass="ms-formlabel datagridfixedheader"/>
<headerstyle backcolor="#006699" font-bold="true" forecolor="white" />
</asp:gridview>

19.gridview数据导入excel/excel数据读入gridview

效果图:

灵活掌握asp.net中gridview控件的多种使用方法(下)

解决方案:
页面增加一个按钮,单击事件添加如下方法:

protected void button1_click(object sender, eventargs e)
{
export("application/ms-excel", "学生成绩报表.xls");
}

private void export(string filetype, string filename)
{
response.charset = "gb2312";
response.contentencoding = system.text.encoding.utf7;
response.appendheader("content-disposition", "attachment;filename=" + httputility.urlencode(filename, encoding.utf8).tostring());
response.contenttype = filetype;
this.enableviewstate = false;
stringwriter tw = new stringwriter();
htmltextwriter hw = new htmltextwriter(tw);
gridview1.rendercontrol(hw);
response.write(tw.tostring());
response.end();
}
//如果没有下面方法会报错类型“gridview”的控件“gridview1”必须放在具有 runat=server 的窗体标记内
public override void verifyrenderinginserverform(control control)
{
}

还有由于是文件操作所以要引入名称空间io和text

后台代码:

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;
using system.io;
using system.text;
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();

}
}

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();
}

protected void button1_click(object sender, eventargs e)
{
export("application/ms-excel", "学生成绩报表.xls");
}

private void export(string filetype, string filename)
{
response.charset = "gb2312";
response.contentencoding = system.text.encoding.utf7;
response.appendheader("content-disposition", "attachment;filename=" + httputility.urlencode(filename, encoding.utf8).tostring());
response.contenttype = filetype;
this.enableviewstate = false;
stringwriter tw = new stringwriter();
htmltextwriter hw = new htmltextwriter(tw);
gridview1.rendercontrol(hw);
response.write(tw.tostring());
response.end();
}
public override void verifyrenderinginserverform(control control)
{
}

}

前台:

<asp:gridview id="gridview1" runat="server" cellpadding="3"
backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" font-size="12px" >
<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:boundfield datafield="邮政编码" headertext="邮政编码" />
<asp:boundfield datafield="起薪" headertext="起薪" />

</columns>
<rowstyle forecolor="#000066" />
<selectedrowstyle backcolor="#669999" font-bold="true" forecolor="white" />
<pagerstyle backcolor="white" forecolor="#000066" horizontalalign="left" cssclass="ms-formlabel datagridfixedheader"/>
<headerstyle backcolor="#006699" font-bold="true" forecolor="white" />
</asp:gridview>
<asp:button id="button1" runat="server" onclick="button1_click" text="导出" />

读取excel数据的代码:这个很简单的

private dataset createdatasource()
{
string strcon;
strcon = "provider=microsoft.jet.oledb.4.0;data source=" + server.mappath("excel.xls") + "; extended properties=excel 8.0;";
oledbconnection olecon = new oledbconnection(strcon);
oledbdataadapter myda = new oledbdataadapter("select * from [sheet1$]", strcon);
dataset myds = new dataset();
myda.fill(myds);
return myds;
}
protected void button1_click(object sender, eventargs e)
{
gridview1.datasource = createdatasource();
gridview1.databind();
}

为大家附3个精彩的专题:

asp.net控件使用手册

asp.net数据绑定控件使用汇总

asp.net控件使用汇总

以上就是关于asp.net中gridview控件的多种使用方法,很全面,目的就是想让亲们玩转gridview控件,希望大家喜欢小编整理的这两篇文章。

上一篇:

下一篇: