datagrid的模板列可以方便的定制所需要的样式,比如上图:
在编辑状态的时候学院是下拉框,选择了当前的学院,但是如果学院很多,下拉框会很长,找起来也会很麻烦,所以可能需要再增加一个查找的功能。这样一个列完全可以通过模板列来实现,可是如果项目中有很多这样的需求,添加这么多复杂的模板列一来很麻烦,二来也有代码冗余,没有重用性,为此,我们可以尝试定制自己的datagridcolumn(类似已经存在的hyperlinkcolumn)来为这个列进行小小的封装。
先建立一个类文件:
using system;
using system.data;
using system.web.ui;
using system.web.ui.webcontrols;
namespace csdn
{
public class mycolumn:datagridcolumn
{
public string datatextfield;
public string datavaluefield;
public datatable datasource;
public override void initializecell(tablecell cell,int columnindex,listitemtype itemtype)
{
base.initializecell(cell,columnindex,itemtype);
switch(itemtype)
{
case listitemtype.header:
cell.text=this.headertext;
break;
case listitemtype.item:case listitemtype.alternatingitem:
cell.databinding+=new eventhandler(this.cell_itemdatabinding);
break;
case listitemtype.edititem:
cell.databinding +=new eventhandler(cell_edititemdatabinding);
dropdownlist ddl=new dropdownlist();
cell.controls.add(ddl);
textbox t=new textbox();
t.width=80;
cell.controls.add(t);
button b=new button();
b.text=“查找“;
b.click+=new eventhandler(this.btn_click);
cell.controls.add(b);
break;
}
}
private void cell_itemdatabinding(object sender, eventargs e)
{
tablecell cell=(tablecell)sender;
datagriditem dgi=(datagriditem)cell.namingcontainer;
cell.text=(databinder.eval(dgi.dataitem,this.datatextfield)).tostring();
}
private void cell_edititemdatabinding(object sender,eventargs e)
{
tablecell cell=(tablecell)sender;
dropdownlist ddl=(dropdownlist)cell.controls[0];
datagriditem dgi=(datagriditem)cell.namingcontainer;
for(int i=0;i<this.datasource.rows.count;i++)
ddl.items.add(new listitem(this.datasource.rows[i][this.datatextfield].tostring(),this.datasource.rows[i][this.datavaluefield].tostring()));
ddl.items.findbyvalue((databinder.eval(dgi.dataitem,this.datavaluefield)).tostring()).selected=true;
}
private void btn_click(object sender,eventargs e)
{
tablecell cell=(tablecell)(((button)sender).parent);
dropdownlist ddl=(dropdownlist)cell.controls[0];
textbox t=(textbox)cell.controls[1];
datagriditem dgi=(datagriditem)cell.namingcontainer;
listitem li=ddl.items.findbytext(t.text);
if(li!=null)
{
ddl.selectedindex=-1;
li.selected=true;
}
}
}
}
using system.data;
using system.web.ui;
using system.web.ui.webcontrols;
namespace csdn
{
public class mycolumn:datagridcolumn
{
public string datatextfield;
public string datavaluefield;
public datatable datasource;
public override void initializecell(tablecell cell,int columnindex,listitemtype itemtype)
{
base.initializecell(cell,columnindex,itemtype);
switch(itemtype)
{
case listitemtype.header:
cell.text=this.headertext;
break;
case listitemtype.item:case listitemtype.alternatingitem:
cell.databinding+=new eventhandler(this.cell_itemdatabinding);
break;
case listitemtype.edititem:
cell.databinding +=new eventhandler(cell_edititemdatabinding);
dropdownlist ddl=new dropdownlist();
cell.controls.add(ddl);
textbox t=new textbox();
t.width=80;
cell.controls.add(t);
button b=new button();
b.text=“查找“;
b.click+=new eventhandler(this.btn_click);
cell.controls.add(b);
break;
}
}
private void cell_itemdatabinding(object sender, eventargs e)
{
tablecell cell=(tablecell)sender;
datagriditem dgi=(datagriditem)cell.namingcontainer;
cell.text=(databinder.eval(dgi.dataitem,this.datatextfield)).tostring();
}
private void cell_edititemdatabinding(object sender,eventargs e)
{
tablecell cell=(tablecell)sender;
dropdownlist ddl=(dropdownlist)cell.controls[0];
datagriditem dgi=(datagriditem)cell.namingcontainer;
for(int i=0;i<this.datasource.rows.count;i++)
ddl.items.add(new listitem(this.datasource.rows[i][this.datatextfield].tostring(),this.datasource.rows[i][this.datavaluefield].tostring()));
ddl.items.findbyvalue((databinder.eval(dgi.dataitem,this.datavaluefield)).tostring()).selected=true;
}
private void btn_click(object sender,eventargs e)
{
tablecell cell=(tablecell)(((button)sender).parent);
dropdownlist ddl=(dropdownlist)cell.controls[0];
textbox t=(textbox)cell.controls[1];
datagriditem dgi=(datagriditem)cell.namingcontainer;
listitem li=ddl.items.findbytext(t.text);
if(li!=null)
{
ddl.selectedindex=-1;
li.selected=true;
}
}
}
}
然后为页面添加这个自定义列:
<%@ page language=“c#“ codebehind=“webform67.aspx.cs“ autoeventwireup=“false“ inherits=“csdn.webform67“ %>
<%@ register tagprefix=“mydatagridcolumn“ assembly=“csdn“ namespace=“csdn“%>
<!doctype html public “-//w3c//dtd html 4.0 transitional//en” >
<html>
<head>
<title>test</title>
<meta http-equiv=”content-type” content=”text/html; charset=gb2312″>
<meta content=”microsoft visual studio .net 7.1″ name=”generator”>
<meta content=”c#” name=”code_language”>
<meta content=”javascript” name=”vs_defaultclientscript”>
<meta content=”http://schemas.microsoft.com/intellisense/ie5″ name=”vs_targetschema”>
<link href=”css.css” type=”text/css” rel=”stylesheet”>
</head>
<body>
<form id=”form1″ method=”post” runat=”server”>
<asp:datagrid id=”datagrid1″ runat=”server” datakeyfield=”stuid” cellspacing=”1″ borderwidth=”0px”
oneditcommand=”edit” oncancelcommand=”cancel” onupdatecommand=”update” cellpadding=”5″ cssclass=”border”
autogeneratecolumns=”false”>
<itemstyle cssclass=”item”></itemstyle>
<headerstyle cssclass=”header”></headerstyle>
<columns>
<asp:boundcolumn headertext=”姓名” datafield=”stuname”></asp:boundcolumn>
<mydatagridcolumn:mycolumn headertext=”学院” datatextfield=”depname” datavaluefield=”depid”></mydatagridcolumn:mycolumn>
<asp:editcommandcolumn buttontype=”pushbutton” updatetext=”更新” canceltext=”取消” edittext=”编辑”></asp:editcommandcolumn>
</columns>
</asp:datagrid>
</form>
</body>
</html>
<%@ register tagprefix=“mydatagridcolumn“ assembly=“csdn“ namespace=“csdn“%>
<!doctype html public “-//w3c//dtd html 4.0 transitional//en” >
<html>
<head>
<title>test</title>
<meta http-equiv=”content-type” content=”text/html; charset=gb2312″>
<meta content=”microsoft visual studio .net 7.1″ name=”generator”>
<meta content=”c#” name=”code_language”>
<meta content=”javascript” name=”vs_defaultclientscript”>
<meta content=”http://schemas.microsoft.com/intellisense/ie5″ name=”vs_targetschema”>
<link href=”css.css” type=”text/css” rel=”stylesheet”>
</head>
<body>
<form id=”form1″ method=”post” runat=”server”>
<asp:datagrid id=”datagrid1″ runat=”server” datakeyfield=”stuid” cellspacing=”1″ borderwidth=”0px”
oneditcommand=”edit” oncancelcommand=”cancel” onupdatecommand=”update” cellpadding=”5″ cssclass=”border”
autogeneratecolumns=”false”>
<itemstyle cssclass=”item”></itemstyle>
<headerstyle cssclass=”header”></headerstyle>
<columns>
<asp:boundcolumn headertext=”姓名” datafield=”stuname”></asp:boundcolumn>
<mydatagridcolumn:mycolumn headertext=”学院” datatextfield=”depname” datavaluefield=”depid”></mydatagridcolumn:mycolumn>
<asp:editcommandcolumn buttontype=”pushbutton” updatetext=”更新” canceltext=”取消” edittext=”编辑”></asp:editcommandcolumn>
</columns>
</asp:datagrid>
</form>
</body>
</html>
后台代码如下:
using system;
using system.collections;
using system.componentmodel;
using system.data;
using system.data.sqlclient;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
namespace csdn
{
/// <summary>
/// webform67 的摘要说明。
/// </summary>
public class webform67 : system.web.ui.page
{
protected system.web.ui.webcontrols.datagrid datagrid1;
private void page_load(object sender, system.eventargs e)
{
// 在此处放置用户代码以初始化页面
if(!ispostback)
{
setbind();
}
}
protected void setbind()
{
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings[“conn“]);
sqldataadapter da=new sqldataadapter(“select * from stu,dep where stu.studepid=dep.depid“,conn);
dataset ds=new dataset();
da.fill(ds);
this.datagrid1.datasource=ds.tables[0];
this.datagrid1.databind();
}
protected void edit(object sender,datagridcommandeventargs e)
{
this.datagrid1.edititemindex=e.item.itemindex;
setbind();
}
protected void cancel(object sender,datagridcommandeventargs e)
{
this.datagrid1.edititemindex=-1;
setbind();
}
protected void update(object sender,datagridcommandeventargs e)
{
if(e.item.itemtype==listitemtype.edititem)
{
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings[“conn“]);
sqlcommand comm=new sqlcommand(“update stu set stuname=@name,studepid=@depid where stuid=@id“,conn);
sqlparameter parm1=new sqlparameter(“@name“,sqldbtype.nvarchar,50);
parm1.value=((textbox)e.item.cells[0].controls[0]).text;
sqlparameter parm2=new sqlparameter(“@depid“,sqldbtype.int);
parm2.value=((dropdownlist)e.item.cells[1].controls[0]).selectedvalue;
sqlparameter parm3=new sqlparameter(“@id“,sqldbtype.int);
parm3.value=this.datagrid1.datakeys[e.item.itemindex];
comm.parameters.add(parm1);
comm.parameters.add(parm2);
comm.parameters.add(parm3);
conn.open();
comm.executenonquery();
conn.close();
this.datagrid1.edititemindex=-1;
setbind();
}
}
#region web 窗体设计器生成的代码
override protected void oninit(eventargs e)
{
//
// codegen: 该调用是 asp.net web 窗体设计器所必需的。
//
initializecomponent();
base.oninit(e);
}
/// <summary>
/// 设计器支持所需的方法 – 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
this.datagrid1.itemdatabound += new system.web.ui.webcontrols.datagriditemeventhandler(this.datagrid1_itemdatabound);
this.load += new system.eventhandler(this.page_load);
}
#endregion
private void datagrid1_itemdatabound(object sender, system.web.ui.webcontrols.datagriditemeventargs e)
{
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings[“conn“]);
sqldataadapter da=new sqldataadapter(“select * from dep“,conn);
dataset ds=new dataset();
da.fill(ds);
((mycolumn)this.datagrid1.columns[1]).datasource=ds.tables[0];
}
}
}
using system.collections;
using system.componentmodel;
using system.data;
using system.data.sqlclient;
using system.drawing;
using system.web;
using system.web.sessionstate;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.htmlcontrols;
namespace csdn
{
/// <summary>
/// webform67 的摘要说明。
/// </summary>
public class webform67 : system.web.ui.page
{
protected system.web.ui.webcontrols.datagrid datagrid1;
private void page_load(object sender, system.eventargs e)
{
// 在此处放置用户代码以初始化页面
if(!ispostback)
{
setbind();
}
}
protected void setbind()
{
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings[“conn“]);
sqldataadapter da=new sqldataadapter(“select * from stu,dep where stu.studepid=dep.depid“,conn);
dataset ds=new dataset();
da.fill(ds);
this.datagrid1.datasource=ds.tables[0];
this.datagrid1.databind();
}
protected void edit(object sender,datagridcommandeventargs e)
{
this.datagrid1.edititemindex=e.item.itemindex;
setbind();
}
protected void cancel(object sender,datagridcommandeventargs e)
{
this.datagrid1.edititemindex=-1;
setbind();
}
protected void update(object sender,datagridcommandeventargs e)
{
if(e.item.itemtype==listitemtype.edititem)
{
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings[“conn“]);
sqlcommand comm=new sqlcommand(“update stu set stuname=@name,studepid=@depid where stuid=@id“,conn);
sqlparameter parm1=new sqlparameter(“@name“,sqldbtype.nvarchar,50);
parm1.value=((textbox)e.item.cells[0].controls[0]).text;
sqlparameter parm2=new sqlparameter(“@depid“,sqldbtype.int);
parm2.value=((dropdownlist)e.item.cells[1].controls[0]).selectedvalue;
sqlparameter parm3=new sqlparameter(“@id“,sqldbtype.int);
parm3.value=this.datagrid1.datakeys[e.item.itemindex];
comm.parameters.add(parm1);
comm.parameters.add(parm2);
comm.parameters.add(parm3);
conn.open();
comm.executenonquery();
conn.close();
this.datagrid1.edititemindex=-1;
setbind();
}
}
#region web 窗体设计器生成的代码
override protected void oninit(eventargs e)
{
//
// codegen: 该调用是 asp.net web 窗体设计器所必需的。
//
initializecomponent();
base.oninit(e);
}
/// <summary>
/// 设计器支持所需的方法 – 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void initializecomponent()
{
this.datagrid1.itemdatabound += new system.web.ui.webcontrols.datagriditemeventhandler(this.datagrid1_itemdatabound);
this.load += new system.eventhandler(this.page_load);
}
#endregion
private void datagrid1_itemdatabound(object sender, system.web.ui.webcontrols.datagriditemeventargs e)
{
sqlconnection conn=new sqlconnection(system.configuration.configurationsettings.appsettings[“conn“]);
sqldataadapter da=new sqldataadapter(“select * from dep“,conn);
dataset ds=new dataset();
da.fill(ds);
((mycolumn)this.datagrid1.columns[1]).datasource=ds.tables[0];
}
}
}
这个例子可能稍微复杂了点(列中放了3个控件),但是原理比较简单,其实简化一下,我们可以封装自己的dropdownlistcolumn、checkboxcolumn等单控件列。