namespace csdn
{
/// <summary>
/// WebForm30 的摘要说明。
/// </summary>
public class WebForm30 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DataGrid DataGrid1;
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
BindGrid();
}
CreateDataGrid();//进行一些DataGrid的设置
}
protected void CreateDataGrid()
{
DataGrid1.AutoGenerateColumns=false;//不启用自动生成列
DataGrid1.CssClass="border";//边框样式
DataGrid1.BorderWidth=0;
DataGrid1.CellSpacing=1;
DataGrid1.CellPadding=5;
DataGrid1.ItemStyle.CssClass="item";//普通列样式
DataGrid1.HeaderStyle.CssClass="header";//头样式
DataGrid1.PagerStyle.CssClass="header";//页脚样式
DataGrid1.DataKeyField="stuid";//主键字段
DataGrid1.AllowPaging=true;//允许分页
DataGrid1.PageSize=5;//分页大小
DataGrid1.PagerStyle.Mode=PagerMode.NumericPages;//数字形式分页
EditCommandColumn ecc=new EditCommandColumn();//更新按钮列
ecc.ButtonType=ButtonColumnType.PushButton;//下压按钮
ecc.EditText="编辑";
ecc.CancelText="取消";
ecc.UpdateText="更新";//按钮文字
DataGrid1.Columns.Add(ecc);//增加按钮列
DataGrid1.EditCommand+=new DataGridCommandEventHandler(DataGrid1_EditCommand);
DataGrid1.UpdateCommand+=new DataGridCommandEventHandler(DataGrid1_UpdateCommand);
DataGrid1.CancelCommand+=new DataGridCommandEventHandler(DataGrid1_CancelCommand);//更新、取消、编辑事件注册
DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(DataGrid1_PageIndexChanged);//分页事件注册,这里需要注意注册事件代码的位置,不能放到BindGrid()中
SetBind(); //绑定数据
}
protected void BindGrid()
{
TemplateColumn tm=new TemplateColumn();
tm.ItemTemplate=new ColumnTemplate1();//普通列
tm.EditItemTemplate=new ColumnTemplate2();//编辑列
tm.HeaderText="姓名";
DataGrid1.Columns.AddAt(0,tm);//在第一列增加第一个模板列
TemplateColumn tm2=new TemplateColumn();
tm2.ItemTemplate=new ColumnTemplate3();
tm2.EditItemTemplate=new ColumnTemplate4();
tm2.HeaderText="学院";
DataGrid1.Columns.AddAt(1,tm2);//在第二列增加第一个模板列
DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(DataGrid1_ItemDataBound);//数据绑定事件注册,这里需要注意注册事件代码的位置
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,"table1");
this.DataGrid1.DataSource=ds.Tables["table1"];
this.DataGrid1.DataBind();
}
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,"table1");
if(e.Item.ItemType==ListItemType.EditItem)
{
DropDownList ddl=(DropDownList)e.Item.FindControl("dep");
ddl.DataSource=ds.Tables["table1"];
ddl.DataTextField="depname";
ddl.DataValueField="depid";
ddl.DataBind();
ddl.Items.FindByValue(Convert.ToString(DataBinder.Eval(e.Item.DataItem,"depid"))).Selected=true;
}
}
private void DataGrid1_EditCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
this.DataGrid1.EditItemIndex=e.Item.ItemIndex;
BindGrid();
}
private void DataGrid1_CancelCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
this.DataGrid1.EditItemIndex=-1;
BindGrid();
}
private void DataGrid1_UpdateCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
string uid=e.Item.UniqueID+":";//注意别遗漏冒号
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=Request.Form[uid+"name"].ToString();
SqlParameter parm2=new SqlParameter("@depid",SqlDbType.Int);
parm2.Value=Request.Form[uid+"dep"].ToString();;
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;
BindGrid();
//之所以不能采用以前的((TextBox)e.Item.FindControl("name")).Text来取得数据时因为,DataGrid列是动态添加的,根本取不到
}
private void DataGrid1_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e)
{
this.DataGrid1.CurrentPageIndex=e.NewPageIndex;
BindGrid();
}
#region Web 窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 设计器支持所需的方法 - 不要使用代码编辑器修改
/// 此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
}
public class ColumnTemplate1 : ITemplate
{
public void InstantiateIn(Control container)
{
LiteralControl l = new LiteralControl();
l.DataBinding += new EventHandler(this.OnDataBinding);
container.Controls.Add(l);
}
public void OnDataBinding(object sender, EventArgs e)
{
LiteralControl l = (LiteralControl) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView)container.DataItem)["stuname"].ToString();
}
}
public class ColumnTemplate2 : ITemplate
{
public void InstantiateIn(Control container)
{
TextBox t = new TextBox();
t.Width=88;
t.ID="name";//需要给一个id,在Request.Form的时候可以取
t.DataBinding += new EventHandler(this.OnDataBinding);
container.Controls.Add(t);
}
public void OnDataBinding(object sender, EventArgs e)
{
TextBox t= (TextBox) sender;
DataGridItem container = (DataGridItem) t.NamingContainer;
t.Text = ((DataRowView)container.DataItem)["stuname"].ToString();//绑定stuname字段
}
}
public class ColumnTemplate3 : ITemplate
{
public void InstantiateIn(Control container)
{
LiteralControl l = new LiteralControl();
l.DataBinding += new EventHandler(this.OnDataBinding);
container.Controls.Add(l);
}
public void OnDataBinding(object sender, EventArgs e)
{
LiteralControl l = (LiteralControl) sender;
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView)container.DataItem)["depname"].ToString();
}
}
public class ColumnTemplate4 : ITemplate
{
public void InstantiateIn(Control container)
{
DropDownList dpl = new DropDownList();
dpl.ID="dep";
container.Controls.Add(dpl);
}//这里没有为这个下拉框进行数据绑定,在DataGrid1的ItemDataBound中进行了这个操作
}
}
代码比较简单,在代码中有注释简单的解释。
补充2点:(1)这次的DataGrid是在设计生成的,不是上次的运行时,后者会造成更新的紊乱;(2)处于简单,代码中模板列类没有很好的封装,在运用的时候还是应该对字段和模板列类型(ListItemType)进行封装
DataBase:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[stu]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[stu]
GO
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[dep]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[dep]
GO
CREATE TABLE [dbo].[stu] (
[stuid] [int] IDENTITY (1, 1) NOT NULL ,
[studepid] [int] NULL ,
[stuname] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[dep] (
[depid] [int] IDENTITY (1, 1) NOT NULL ,
[depname] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
GO