2017-08-28 158 views
0

我在GridView中動態創建了CheckBox,但CheckedChanged事件在點擊兩次時觸發。動態創建的CheckBoxs在第二次點擊時觸發,而不是第一次

哪裏錯了?

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) 
{ 
    // check if it's not a header and footer 
    if (e.Row.RowType == DataControlRowType.Row) 
    { 
     CheckBox chk = new CheckBox(); 

     chk.AutoPostBack = true; 

     // add checked changed event to checkboxes 
     chk.CheckedChanged += new EventHandler(chk_CheckedChanged); 

     e.Row.Cells[1].Controls.Add(chk); // add checkbox to second column 
    } 
} 
+0

是否給Checked字段一個初始值會改變什麼?即:chk.Checked = false; – lancew

回答

0

您在GridView中的兩個OnRowCreatedOnRowDataBound事件使用下面的代碼。

這將僅在第一次點擊時觸發CheckedChanged

if (e.Row.RowType == DataControlRowType.DataRow) 
{ 
    CheckBox chk = e.Row.Cells[1].FindControl("chk") as CheckBox; 
    if (chk == null) 
    { 
     chk = new CheckBox(); 
     chk.ID = "CheckBox1"; 
     chk.AutoPostBack = true; 
     chk.CheckedChanged += new EventHandler(chk_CheckedChanged); 

     e.Row.Cells[1].Controls.Add(chk); 
    } 
} 
相關問題