(原创)DataGrid动态添加模板列的一个例子
数据源结构同http://www.cnblogs.com/lovecherry/archive/2005/03/25/125525.html
表dep:depid(标识主键),depname(学院名字)
表stu:stuid(标识主键),stuname(学生名字),studepid(学院id=表dep.depid)
前台:
<%@ Page language="c#" Codebehind="WebForm30.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm30" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<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">
</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
{
DataGrid DataGrid1=new DataGrid();
private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
CreateDataGrid();
}
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.DataKeyField="stuid";
//以上设定DataGrid的样式
TemplateColumn tm=new TemplateColumn();
tm.ItemTemplate=new ColumnTemplate1();
tm.HeaderText="姓名";
DataGrid1.Columns.Add(tm);
//建立第一个模板列
TemplateColumn tm2=new TemplateColumn();
tm2.ItemTemplate=new ColumnTemplate2();
tm2.HeaderText="学院";
DataGrid1.Columns.Add(tm2);
//建立第二个模板列
ButtonColumn bc=new ButtonColumn();
bc.ButtonType=ButtonColumnType.PushButton;
bc.CommandName="del";
bc.Text="删除";
DataGrid1.Columns.Add(bc);
//建立删除按钮列
SetBind();
//填充数据
Page.Controls[1].Controls.Add(DataGrid1);
//给页面的form加入这个DataGrid1
}
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.Item||e.Item.ItemType==ListItemType.AlternatingItem)
{
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_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if(e.CommandName=="del")
{
SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
SqlCommand comm=new SqlCommand("delete from stu where stuid=@id",conn);
SqlParameter parm1=new SqlParameter("@id",SqlDbType.Int);
parm1.Value=this.DataGrid1.DataKeys[e.Item.ItemIndex];
comm.Parameters.Add(parm1);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
SetBind();
}
}
#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);
this.DataGrid1.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.DataGrid1_ItemDataBound);
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);//这里的两个事件千万别忘记,因为DataGrid是后台创建的,这些事件需要自己来写上,vs.net也不会为你创建
}
#endregion
}
public class ColumnTemplate1 : ITemplate
{
//第一个模板列
public void InstantiateIn(Control container)
{
LiteralControl l = new LiteralControl();
l.DataBinding += new EventHandler(this.OnDataBinding);
//数据绑定
container.Controls.Add(l);
//为模板列加入LiteralControl
}
public void OnDataBinding(object sender, EventArgs e)
{
LiteralControl l = (LiteralControl) sender;//LiteralControl发送绑定请求
DataGridItem container = (DataGridItem) l.NamingContainer;
l.Text = ((DataRowView)container.DataItem)["stuname"].ToString();//绑定stuname字段
}
}
public class ColumnTemplate2 : ITemplate
{
//第二个模板列
public void InstantiateIn(Control container)
{
DropDownList dpl = new DropDownList();
dpl.ID="dep";
container.Controls.Add(dpl);
//加入一个id="dep"的下拉框,数据在DataGrid的ItemDataBound中绑定
}
}
}