GridView 动态添加绑定列和模板列

时间:2022-10-02 13:53:37

动态添加绑定列很简单:例如:

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);
动态绑定模板列稍微复杂:

首先创建一个类,该类时继承了System.Web.UI.ITemplate

public class MyTemplate:System.Web.UI.ITemplate
{
    private string proName;
    public MyTemplate()
    {
        //
        //TODO: 在此处添加构造函数逻辑
        //
    }
    public string ProName//要绑定的数据源字段名称
    {
        set { proName = value; }
        get { return proName; }
    }

public void InstantiateIn(Control container)//关键实现这个方法
    {
        TextBox hi = new TextBox();
        hi.Text = "";
        hi.DataBinding += new EventHandler(hi_DataBinding);//创建数据绑定事件
        container.Controls.Add(hi);
    }

void hi_DataBinding(object sender, EventArgs e)
    {
        TextBox hi = (TextBox)sender;
        GridViewRow container = (GridViewRow)hi.NamingContainer;
        //关键位置
        //使用DataBinder.Eval绑定数据
        //ProName,MyTemplate的属性.在创建MyTemplate实例时,为此属性赋值(数据源字段)
        hi.Attributes.Add("onclick", "alert('" + DataBinder.Eval(container.DataItem, ProName).ToString() + "');");
    
}
上面时创建了一个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";//数据源字段
            tf.ItemTemplate = mt;
            this.GridView1.Columns.Add(tf);
            this.GridView1.DataSource = ds;
            this.GridView1.DataBind();
这样就会添加了一个textbox的模板列;