如何在 ASP.NET 的 GridView 单元格中检索动态生成的 TextBox 的内容

How to retrieve the content of a dynamically generated TextBox in a GridView cell in ASP.NET

我有一个 GridView,行代表学生,列代表他们在不同科目中的分数。学生人数是可变的。因此,GridView 中的行数是未知的。用户在输入分数时将指定运行时的学生人数。每行的每个主题都有一个文本框。

用户单击计算按钮后,我需要检索所有 TextBoxes 中的值。

我尝试了以下代码:

protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)

    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            List<TextBox> list = new List<TextBox>(); 
            if (ViewState["Table"] != null)
                Assessments = (DataTable)ViewState["Table"]; 
            int count = 1;
            foreach (DataRow row in Assessments.Rows)
            {
                TextBox txt = new TextBox();
                txt.ID = "AsTxt"; 
                txt.Text = string.Empty;
                txt.TextChanged += OnTextChanged; 
                e.Row.Cells[count].Controls.Add(txt);
                count += 2;
                listd.Add((e.Row.DataItem as DataRowView).Row[0].ToString() + "Txt");
            }
        }
    }

对于计算按钮:

protected void CalculateBtn_Click(object sender, EventArgs e)
        {
            GridViewRow rr = GridView2.Rows[0];
            TextBox rrrr = (rr.FindControl("AsTxt") as TextBox); 
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rrrr.Text + "')", true);
        }

代码没有像往常一样工作returns NullReferenceException,即 rrrr 为 null。

有人可以帮我解决这个问题吗?

我认为您可以在页面加载时添加数据,这样 asp.net 将自动保留视图状态。所以你的控件将存在。您始终需要在您更改的页面加载值中添加控件,asp.net 会自动跟踪。

您需要根据行中的单元格编号访问文本框

protected void CalculateBtn_Click(object sender, EventArgs e)
        {
            GridViewRow rr = GridView2.Rows[0];

            TextBox rrrr = (rr.Cells[0].FindControl("AsTxt") as TextBox); 
            ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + rrrr.Text + "')", true);
        }

目前我在单元格索引中输入了 0,请根据您的 gridview 行更改它。