Aymen Kareem Aymen Kareem - 26 days ago 11
ASP.NET (C#) Question

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

I have a

GridView
with the rows represents students and columns for their marks in different subjects. The number of students is variable. Thus, the number of rows in the
GridView
is unknown. Users when entering the marks will specify the number of students in runtime. Each row has a TextBox for each subject.

After the user click on calculate button I need to retrieve the values in all the
TextBoxes
.

I tried the following code:

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");
}
}
}


And for the calculation button:

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


The code didn't work as it always returns NullReferenceException, that is rrrr is null.

Can anybody help me with this?

Answer

You need to access the textbox as per cell no in the row

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

Currently I have put 0 as in the cell index, change it as per your gridview row.

Comments