GridView动态添加模板列(数据绑定)

来源:互联网 发布:淘宝店铺页头在线制作 编辑:程序博客网 时间:2024/05/16 23:59

1.创建实现System.Web.UI.ITemplate 接口的新类.


    public class MyTemplate : ITemplate
    {
        private string proName;
        public MyTemplate()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }

        public string ProName//要绑定的数据源字段名称
        {
            set { proName = value; }
            get { return proName; }
        }

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

        void hi_DataBinding(object sender, EventArgs e)
        {
            HtmlImage hi = (HtmlImage)sender;
            GridViewRow container = (GridViewRow)hi.NamingContainer;
            //关键位置
            //使用DataBinder.Eval绑定数据
            //ProName,MyTemplate的属性.在创建MyTemplate实例时,为此属性赋值(数据源字段)
            hi.Attributes.Add("onclick", "alert('" + DataBinder.Eval(container.DataItem, ProName).ToString() + "');");
        }
    }


 2.*.aspx页面后台cs代码
        if (!this.IsPostBack)
        {
            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 = "m_task_name";//数据源字段
            tf.ItemTemplate = mt;
            this.GridView1.Columns.Add(tf);
            this.GridView1.DataSource = ds;
            this.GridView1.DataBind();
        }

原创粉丝点击