首先,动态创建的CheckBox会在第二次单击时触发

时间:2017-08-28 16:14:07

标签: c# asp.net gridview checkbox dynamically-generated

我在GridView中动态创建了CheckBoxs,但是当我点击两次时,CheckedChanged事件会触发。

哪里错了?

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
    }
}

1 个答案:

答案 0 :(得分: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);
    }
}