[問題] GridView 使用TemplateField問題

看板C_Sharp作者 (winner)時間16年前 (2009/06/24 20:26), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/2 (看更多)
我在gridview1中想要動態加入CheckBox 利用TemplateField實做 並在button1按下時 檢查有那些CheckBox被選擇 程式碼如下 protected void initiallize(DataSet ds) { TemplateField customField = new TemplateField(); customField.ItemTemplate = new GridViewTemplate("2"); GridView1.Columns.Add(customField); GridView1.DataSource = ds; GridView1.DataBind(); } public class GridViewTemplate : System.Web.UI.ITemplate { private string _id; public GridViewTemplate(string id) { _id = id; } public void InstantiateIn(System.Web.UI.Control container) { CheckBox cb = new CheckBox(); cb.ID = "CheckBox" + _id.ToString(); container.Controls.Add(cb); } } protected void Button1_Click(object sender, EventArgs e) { LabelMsg.Text = ""; for (int i = 0; i < GridView1.Rows.Count; i++) { if(((CheckBox)GridView1.Rows[i].Cells[0] .FindControl("CheckBox2")).Checked) { LabelMsg.Text += i.ToString(); } } } 執行後 GridView1的確也將CheckBox加入了 但是當Button1按下時 在黃色行有error 偵錯發現 GridView1.Rows[i].Cells[0].Controls.Count = 0 但是在initiallize function結尾時(綠色處)檢查 GridView1.Rows[i].Cells[0].FindControl("CheckBox2")沒問題 請問一下如何解決?? 或是有更好的實作方法?? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.20.98.2
文章代碼(AID): #1AGXkBF_ (C_Sharp)
文章代碼(AID): #1AGXkBF_ (C_Sharp)