Aymen Kareem Aymen Kareem - 1 month ago 6
ASP.NET (C#) Question

Retrieving a Dynamically Generated TextBox Content in a GridView in ASP.NET

I have the following RowDataBound method for GridView2

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 the following event (Button Click) to retrieve whatever written in the text box in the GridView

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


I always get NullReferenceException. That mean the TextBox object (rrrr) is null always. I am sure that the text object sits in GridView2.Rows[0].

Why is this happening?

Answer

This is known issue with the Dynamical created controls in asp. So if you want to use the created control on your postback then I suggest that you declare your controls outside the page_int and do your initialization in the init then use them with their name instead of find control.

Look at this blog this might help you

http://techbrij.com/retrieve-value-of-dynamic-controls-in-asp-net