<%@ Page language="c#" Codebehind="WebForm30.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm30" %>
<!DOCTYPE HTML PUBLIC "-//W
<HTML>
<HEAD>
<title>WebForm30</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<link href="css.css" rel="stylesheet" type="text/css">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<asp:DataGrid ID="DataGrid1" Runat="server"></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>
/// 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)进行封装