找不到在rowdatabound网格视图上添加的复选框控件

时间:2013-02-07 13:46:15

标签: c# asp.net gridview dynamic postback

我已经通过

添加了控制权
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chk = new CheckBox();
        chk.EnableViewState = true;
        chk.Enabled = true;
        chk.ID = "chkb";


        DataRowView dr = (DataRowView)e.Row.DataItem;
        chk.Checked = (dr[0].ToString() == "true");


        e.Row.Cells[1].Controls.Add(chk);
        e.Row.TableSection = TableRowSection.TableBody;
    }

并尝试通过

查找
     if (GridView2.Rows.Count>0)
    {
        foreach (GridViewRow row in GridView2.Rows)
        {
            CheckBox cb =(CheckBox) GridView2.Rows[2].Cells[1].FindControl("chkb");
            if (cb != null && cb.Checked)
            {
                Response.Write("yest");
            }

        }
    }

但是我找不到它...... 实际上我的问题是我需要创建一个动态列表..因为我正在使用gridview

1 个答案:

答案 0 :(得分:1)

您需要在每次回发时创建动态控件,因为它在当前生命周期的末尾处理。但RowDataBound仅在您GridView通常仅if(!IsPostBack)(通常在页面加载时)完成时将触发。

您应该在RowCreated中创建动态控件,而不是在每次回发时调用。如果需要,您可以在RowDataBound中对这些控件进行数据绑定,因为首先会触发RowCreated

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        CheckBox chk = new CheckBox();
        chk.EnableViewState = true;
        chk.Enabled = true;
        chk.ID = "chkb";
        e.Row.Cells[1].Controls.Add(chk);
    }
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        var chk = (CheckBox)e.Row.FindControl("chkb");
        // databind it here according to the DataSource in e.Row.DataItem
    }
}