1. 程式人生 > >GridView動態新增模板列並自動繫結資料

GridView動態新增模板列並自動繫結資料

 protected void ForeachCheckBox()
        {
            gv.Columns.Clear();

            BoundField bf = null;
            TemplateField tf = null;
            foreach (Control c in drag.Controls)//遍歷所有控制元件
            {
                if (c is CheckBox)//只遍歷CheckBox控制元件
                {
                    if (((CheckBox)c).Checked)
                    {
                        //bf = new BoundField();
                        //bf.HeaderText = ((CheckBox)c).Text;
                        //bf.DataField = ((CheckBox)c).ToolTip;
                        //gv.Columns.Add(bf);
                        tf =new TemplateField();
                        tf.ShowHeader = true;
                        tf.HeaderTemplate = new GridViewTemplate(DataControlRowType.Header, ((CheckBox)c).Text, ((CheckBox)c).ToolTip);//新增的列標題  
                        tf.ItemTemplate = new GridViewTemplate(DataControlRowType.DataRow, ((CheckBox)c).Text, ((CheckBox)c).ToolTip);//內容列
                        gv.Columns.Add(tf);
                    }
                }
            }

        }

public class GridViewTemplate : ITemplate
    {
        private DataControlRowType templateType;
        private string columnName;
        private string dataField;

        public GridViewTemplate(DataControlRowType type, string column,string dataField)
        {
            this.templateType = type;
            this.columnName = column;
            this.dataField = dataField;
        }

        public void InstantiateIn(Control container)
        {
            switch (templateType)
            {
                case DataControlRowType.Header:
                    {
                        Label lbl = new Label();
                        lbl.Text = columnName;
                        container.Controls.Add(lbl);
                        break;
                    }
                case DataControlRowType.DataRow:
                    {
                        Label lblContent = new Label();
                        lblContent.ID = container.ClientID;
                        lblContent.DataBinding += new EventHandler(lblContent_DataBinding);
                        container.Controls.Add(lblContent);
                        break;
                    }
                default:
                    break;
            }
        }

        private void lblContent_DataBinding(object sender, EventArgs e)
        {
            Label lbl = (Label)sender;
            GridViewRow container = (GridViewRow)lbl.NamingContainer;
            lbl.Text = ((DataRowView)container.DataItem)[dataField].ToString();
            lbl.ToolTip = lbl.Text;
        }
    }