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等单控件列。