gridview选中,编辑,取消,删除
gridview正反双向排序
gridview和下拉菜单dropdownlist结合
gridview和checkbox结合
鼠标移到gridview某一行时改变该行的背景色方法一
鼠标移到gridview某一行时改变该行的背景色方法二
gridview实现删除时弹出确认对话框
gridview实现自动编号
gridview实现自定义时间货币等字符串格式
gridview实现用“...”代替超长字符串
gridview一般换行与强制换行
gridview显示隐藏某一列
gridview弹出新页面/弹出新窗口
gridview固定表头(不用javascript只用css,2行代码,很好用)
gridview合并表头多重表头无错完美版(以合并3列3行举例)
gridview突出显示某一单元格(例如金额低于多少,分数不及格等)
gridview加入自动求和求平均值小计
gridview数据导入excel/excel数据读入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
{
//清清月儿http://blog.csdn.net/21aspnet
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" 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
{
//清清月儿的博客http://blog.csdn.net/21aspnet
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" 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" 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='<%# 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
{
//清清月儿http://blog.csdn.net/21aspnet
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" />
</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" autopostback="true" font-size="9pt" oncheckedchanged="checkbox2_checkedchanged"
text="全选" />
<asp:button id="button1" runat="server" font-size="9pt" text="取消" ="button1_click" />
<asp:button id="button2" runat="server" font-size="9pt" text="删除" ="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("over", "c=this.style.backgroundcolor;this.style.backgroundcolor='#00a9ff'");
//当鼠标移开时还原背景色
e.row.attributes.add("out", "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" autogeneratecolumns="false" 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("over", "c=this.style.backgroundcolor;this.style.backgroundcolor='#00a9ff'");
// //当鼠标移开时还原背景色
// e.row.attributes.add("out", "this.style.backgroundcolor=c");
// }
//}
//如果是绑定数据行
if (e.row.rowtype == datacontrolrowtype.datarow)
{
//鼠标经过时,行背景色变
e.row.attributes.add("over", "this.style.backgroundcolor='#e6f5fa'");
//鼠标移出时,行背景色变
e.row.attributes.add("out", "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("", "#return confirm('你确认要删除:\"" + e.row.cells[1].text + "\"吗?')");
}
}
}
9.gridview实现自动编号:
效果图:
实现方法:
双击gridview的onrowdatabound事件;
在后台的gridview1_rowdatabound()方法添加代码,最后代码如下所示:
protected void gridview1_rowdatabound(object sender, gridviewroweventargs e)
{
//如果是绑定数据行 //清清月儿http://blog.csdn.net/21aspnet
if (e.row.rowtype == datacontrolrowtype.datarow)
{
////鼠标经过时,行背景色变
//e.row.attributes.add("over", "this.style.backgroundcolor='#e6f5fa'");
////鼠标移出时,行背景色变
//e.row.attributes.add("out", "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("", "#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" autogeneratecolumns="false" 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攻击,安全起见而用的,所以,可以有以下两种方法解决
1、
<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("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" autogeneratecolumns="false" 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
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;
}
后台全部代码:
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("over", "this.style.backgroundcolor='#e6f5fa'");
////鼠标移出时,行背景色变
//e.row.attributes.add("out", "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("", "#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();
}
}
}
11.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。
12.gridview显示隐藏某一列:
本方案为月儿独创,不同于网上其他方式,我觉得用一个checkbox更人性化,这样可以隐藏不必要的列,让用户自己选择需要出现的列,在处理多列时这是一个很好的解决方案!
效果图:
图1-开始
图2-点击显示的checkbox后
解决方案:
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显示隐藏列 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body style="font-size=12px">
<form id="form1" runat="server">
<div>
<asp:gridview id="gridview1" runat="server" autogeneratecolumns="false" 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" autopostback="true" font-size="12px"
oncheckedchanged="checkbox1_checkedchanged" text="显示隐藏家庭住址" /></div>
</form>
</body>
</html>
13.gridview弹出新页面/弹出制定大小位置新窗口:
效果图:
方案一:简单的方法,新窗口不固定大小
<asp:gridview id="gridview1" runat="server" autogeneratecolumns="false" 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="#varwin=window.open('detail.aspx?id={0}',null,'width=300,height=200');window.close();"
datatextfield="lastname" headertext="lastname"></asp:hyperlinkcolumn>
使用的是结合javascript的window.open方法,关于window.open的参数网上有很多帖子,本站也有许多参考
弹出窗口大全 http://blog.csdn.net/21aspnet/archive/2004/10/25/150231.aspx 即可!
14.gridview固定表头(不用javascript只用css!,很好用):
效果图:
代码:
<!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固定表头 清清月儿http://blog.csdn.net/21aspnet </title>
<style>
.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>
</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" autogeneratecolumns="false" 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" >
15.gridview合并表头多重表头无错完美版(以合并3列3行举例)
效果图:
后台代码:
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合并多重表头表头 清清月儿http://blog.csdn.net/21aspnet </title>
</head>
<body >
<form id="form1" runat="server">
<div >
<asp:gridview id="gridview1" runat="server" autogeneratecolumns="false" 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>
16.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" autogeneratecolumns="false" 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>
17.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" autogeneratecolumns="false" 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>
18.gridview数据导入excel/excel数据读入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" autogeneratecolumns="false" 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" ="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();
}
由于时间关系,这个文章先到此。有时间再写,其实还有很多技巧,不过我觉得如果能融汇贯通应该可以举一反三。