動態(tài)添加綁定列很簡單:例如: GridView1.DataSourceID = "SqlDataSource1";
BoundField bf1 = new BoundField();
BoundField bf2 = new BoundField();
BoundField bf3 = new BoundField(); bf1.HeaderText = "Employee ID";
bf1.DataField = "EmployeeID";
bf1.ReadOnly = true;
bf1.SortExpression = "EmployeeID";
bf2.HeaderText = "First Name";
bf2.DataField = "FirstName";
bf2.SortExpression = "FirstName"; bf3.HeaderText = "Last Name";
bf3.DataField = "LastName";
bf3.SortExpression = "LastName"; CommandField cf = new CommandField();
cf.ButtonType = ButtonType.Button;
cf.ShowCancelButton = true;
cf.ShowEditButton = true; GridView1.Columns.Add(bf1);
GridView1.Columns.Add(bf2);
GridView1.Columns.Add(bf3);
GridView1.Columns.Add(cf);
動態(tài)綁定模板列稍微復雜: 首先創(chuàng)建一個類,該類時繼承了System.Web.UI.ITemplate public class MyTemplate:System.Web.UI.ITemplate
{
private string proName;
public MyTemplate()
{
//
//TODO: 在此處添加構(gòu)造函數(shù)邏輯
//
}
public string ProName//要綁定的數(shù)據(jù)源字段名稱
{
set { proName = value; }
get { return proName; }
} public void InstantiateIn(Control container)//關(guān)鍵實現(xiàn)這個方法
{
TextBox hi = new TextBox();
hi.Text = "";
hi.DataBinding += new EventHandler(hi_DataBinding);//創(chuàng)建數(shù)據(jù)綁定事件
container.Controls.Add(hi);
} void hi_DataBinding(object sender, EventArgs e)
{
TextBox hi = (TextBox)sender;
GridViewRow container = (GridViewRow)hi.NamingContainer;
//關(guān)鍵位置
//使用DataBinder.Eval綁定數(shù)據(jù)
//ProName,MyTemplate的屬性.在創(chuàng)建MyTemplate實例時,為此屬性賦值(數(shù)據(jù)源字段)
hi.Attributes.Add("onclick", "alert('" + DataBinder.Eval(container.DataItem, ProName).ToString() + "');");
}
上面時創(chuàng)建了一個textbox的模板, 頁面使用時 2.*.aspx頁面后臺cs代碼
DataSet ds = null;
BLL.model_task bll = new BLL.model_task();
ds = bll.GetList(string.Empty);
TemplateField tf = new TemplateField();
tf.HeaderText = "自定義模板列";
MyTemplate mt = new MyTemplate();
mt.ProName = "ID";//數(shù)據(jù)源字段
tf.ItemTemplate = mt;
this.GridView1.Columns.Add(tf);
this.GridView1.DataSource = ds;
this.GridView1.DataBind();
這樣就會添加了一個textbox的模板列;
|