William
William

Reputation: 330

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?

Upvotes: 0

Views: 967

Answers (2)

Trupti
Trupti

Reputation: 128

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.

Upvotes: 1

Mahesh Malpani
Mahesh Malpani

Reputation: 1989

I think you can add the data on page load so that asp.net will persist the viewstate automatically. So your controls will be present. Always you need to add the controls in page load values changed by you will be tracked by asp.net automatically.

Upvotes: 0

Related Questions