【问题标题】:Dynamically added controls in gridview (checkbox) disappear after postback in asp.net在 asp.net 中回发后,gridview(复选框)中动态添加的控件消失
【发布时间】:2019-06-22 08:36:47
【问题描述】:

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

回帖后复选框消失。

这是我的代码

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

【问题讨论】:

    标签: c# asp.net gridview postback


    【解决方案1】:

    使用动态控件时,您需要在每个 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";
    

    【讨论】:

    • 仍然复选框有空值@vdwwd
    • 感谢@VDWWD 其工作正常,但新问题发生在按钮单击我获取行项目的值时,每当我检查第二行 foreach 的复选框时它总是给出第一行值(grdreport.Rows 中的 GridViewRow 行){ CheckBox checkbox1 = (CheckBox)row.FindControl("cb1"); checkbox1.Checked = true; if (checkbox1.Checked) { string itemname = row.Cells[0].Text;字符串特别 = row.Cells[1].Text;字符串数量 = row.Cells[2].Text; } } }'
    • 您正在循环所有行,因此您必须确保获得正确的行。
    • 如何获取检查行@VDWWD
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 2014-10-22
      • 2018-09-28
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2016-12-17
      相关资源
      最近更新 更多