Search code examples
c#findcontroldynamic-controlsdynamic-tables

Find textbox control in ASP dynamic table


I am dynamically creating a table that contains a textbox. I am doing so with the following code:

foreach (DataRow row in Score_Sheet.Rows) // Loop over the rows.
                {
                    int rowIndex = Score_Sheet.Rows.IndexOf(row); // Not sure if i need this yet

                    Label label = new Label();
                    TextBox txt = new TextBox();
                    txt.Text = row["Value"].ToString();
                    txt.ID = row["Risk"].ToString();
                    label.Text = row["Risk"].ToString() + "      =      ";
                    rows = new TableRow();
                    cell = new TableCell();
                    cell.Controls.Add(label);
                    cell2 = new TableCell();
                    cell2.Controls.Add(txt);


                    rows.Controls.Add(cell);
                    rows.Controls.Add(cell2);
                    SSGrid.Controls.Add(rows);


                }

this is adding a Table to my webpage via this code:

 <asp:Table ID="SSGrid" runat="server"></asp:Table>

the table is populating correctly, however when I try to access the updated value from the textbox in the table I get a null reference exception.

my find control code is this:

TextBox txt_any = (TextBox)SSGrid.FindControl("ANY");
                string anyany = txt_any.Text;
                row1["Value"] = any;

how can I access the values that are being updated in this textbox?

thanks!


Solution

  • Since you are using dynamically generated controls here, for you to access them or their values, you will have to recreate them when the page is postback. This is because dynamic controls lose their state after they have been rendered on the view and the only way to play with them again after postback is to re-create them in code-behind.

    So here, you just need to recreate the table using the code that you use to create it for the first time.

    You can put that code outside the if(!IsPostBack) code block in your Page_Load and this will get you going with this.

    Hope this helps.