asp.net 回发后,在 gridview 中动态添加的控件(复选框)消失

Dynamically added controls in gridview (checkbox) disappear after postback in asp.net

我向网格视图列添加了一个动态创建复选框,但它在单击按钮时为我提供了空值。

复选框在 post 返回后消失。

这是我的代码

protected void grdreport_RowDataBound(object sender, GridViewRowEventArgs e)
{
    int temp = e.Row.Cells.Count;

    temp--;

    if (e.Row.RowType == DataControlRowType.DataRow)
    {

        if (temp >= 3)
        {
            strheadertext1 = grdreport.HeaderRow.Cells[3].Text;

            CheckBox cb1 = new CheckBox();

            cb1.Text = e.Row.Cells[3].Text;

            e.Row.Cells[3].Controls.Add(cb1);

        }

    }
}

在我的按钮上单击我检查复选框值是否被选中的地方是

foreach (GridViewRow item in grdreport.Rows)
{
    if (item.RowType == DataControlRowType.DataRow)
    {
        CheckBox checkbox1 = (CheckBox)item.FindControl("cb1");
        // cb1.Checked = true;
        if (checkbox1.Checked)
        {
        }
    }
}

为了在 PostBack 期间访问动态创建的控件的值,您需要在 OnInit 方法中重新创建具有相同 ID 的控件。在极少数情况下,这是必要的,或者证明您必须付出努力来完成这项工作——尤其是在涉及列表或网格的场景中。

也就是说,您可以使用一些替代方法来仅显示某些项目的复选框。一个想法是添加一个普通的复选框列(或者对于更复杂的场景,一个模板列)。使用代码或 CSS 隐藏您不想看到复选框的行中的复选框。所以对象会在那里,但用户不会在它隐藏的行中看到它。这通常比动态方法容易得多。

使用动态控件时,您需要在每个 PostBack 上重新绑定 GridView 数据。所以通常您会使用 IsPostBack 检查并在其中绑定数据。但是现在不要那样做。

protected void Page_Load(object sender, EventArgs e)
{
    //normally you would bind here
    if (IsPostBack == false)
    {
        GridView1.DataSource = source;
        GridView1.DataBind();
    }

    //but when using dynamic control inside a gridview, bind here
    GridView1.DataSource = source;
    GridView1.DataBind();
}

更新

并且您必须为动态控件提供一个 ID。您正在寻找 cb1,但您从未将该 ID 分配给复选框。

CheckBox cb1 = new CheckBox();
cb1.ID = "cb1";