2014年8月17日 星期日

ASP.NET GridView Code-Behind TemplateField


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TemplateField TF = new TemplateField();
                TF.HeaderTemplate = new GridViewTextTemplate(DataControlRowType.Header, "選擇", "Choose");
                TF.ItemTemplate = new GridViewTextTemplate(DataControlRowType.DataRow, "GridViewCB", "GridViewCB");
                TF.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
                TF.ItemStyle.VerticalAlign = VerticalAlign.Middle;
                TF.ShowHeader = true;
                GridView1.Columns.Add(TF);
            }
        }

        public class GridViewTextTemplate : ITemplate
        {
            private DataControlRowType TemplateType;
            private string ColumnName;
            private string CId;

            public GridViewTextTemplate(DataControlRowType Type, string ColName, string controlId)
            {
                TemplateType = Type;
                ColumnName = ColName;
                CId = controlId;
            }

            public void InstantiateIn(System.Web.UI.Control container)
            {
                switch (TemplateType)
                {
                    case DataControlRowType.Header:
                        Label Lbl = new Label();
                        Lbl.ID = CId;
                        Lbl.Text = ""+ColumnName+"";
                        container.Controls.Add(Lbl);
                        break;

                    case DataControlRowType.DataRow:
                        CheckBox myCheckBox = new CheckBox();
                        myCheckBox.ID = CId;
                       // myCheckBox.DataBinding += new EventHandler(this.CheckBoxDataBinding);
                        container.Controls.Add(myCheckBox);
                        break;

                    default:
                        // Insert code to handle unexpected values.
                        break;

                }
            }

           /* private void CheckBoxDataBinding(object sender, EventArgs e)
            {
                CheckBox myCheckBox = (CheckBox)sender;
                GridViewRow row = (GridViewRow)myCheckBox.NamingContainer;
                myCheckBox.Text = System.Web.UI.DataBinder.Eval(row.DataItem, ColumnName).ToString();
            }*/
        }

沒有留言:

張貼留言