[問題] 抓不到GridView裡的checkbox?

看板C_Sharp作者 (科科)時間14年前 (2009/09/29 22:36), 編輯推噓1(106)
留言7則, 4人參與, 最新討論串1/1
我參考聖殿祭司的.net3.5專家技術手冊I裡面的 動態建立 TemplateField 樣板欄位寫了一支程式 在Gridview裡動態生成checkbox,在Gridview的footer產生一個Button 在按下Button引發的 RowCommand 事件裡抓出已選取的checkbox 現在的問題是RowCommand假如寫成 CheckBox chk; foreach (GridViewRow rowItem in GridView1.Rows) { if (rowItem.RowType == DataControlRowType.DataRow) { chk = (CheckBox)(rowItem.Cells[0].FindControl("cbox")); if (chk.Checked) { } } } 就會引發 Object reference not set to an instance of an object. Error 如果寫成 CheckBox chk; foreach (GridViewRow rowItem in GridView1.Rows) { if (rowItem.RowType == DataControlRowType.DataRow) { chk = (CheckBox)(rowItem.Cells[0].Controls[0]); } } 就會引發Specified argument was out of the range of valid values. Parameter name: index 看起來像是沒抓到CheckBox,難不成CheckBox根本不在那個NamingContainer裡@@ -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.165.170.34

09/29 22:53, , 1F
rowItem.FindControl("cbox") 呢?
09/29 22:53, 1F

09/29 23:27, , 2F
一樣不行阿
09/29 23:27, 2F

09/30 00:08, , 3F
我猜你的CheckBox在該時點並未再次產生,所以找不到
09/30 00:08, 3F

09/30 00:09, , 4F
你應該再RowCommand事件之前要再rebind
09/30 00:09, 4F

09/30 00:11, , 5F
這是常見的動態產生Controls的問題
09/30 00:11, 5F

10/02 14:22, , 6F
你在RowCommand前是否做了DataBind...檢查一下Page_Load
10/02 14:22, 6F

10/02 14:22, , 7F
裡面有沒有設定Postback時 不要再重新Databind GridView
10/02 14:22, 7F
文章代碼(AID): #1AmXjwtD (C_Sharp)