Search code examples
c#asp.netcontrolsweb-controls

saving values of textbox in a loop (asp.net web page)


I've been trying to follow a few tutorials and code examples but something isn't working as I'd expect.

I have a series of textboxes on a webpage and I need to loop through each one and save it's value to the database. The number of textboxes on the page will vary. I load them from a database. They are all added to a table object.

TableCell cellb = new TableCell();
TextBox txtAnswer = new TextBox();
txtAnswer.TextMode = TextBoxMode.MultiLine;
txtAnswer.Rows = 2;
txtAnswer.ID = "field_" + dataRow["fieldID"].ToString();
txtAnswer.Text = "answer"; //this will be got from the database

cellb.Controls.Add(txtAnswer);

so that adds the textbox to the table row. I then have a save button which has the following code

foreach (Control c in Page.Controls)
{
    foreach (Control childc in c.Controls) 
    {
        if (childc is TextBox)
        {
            TextBox tmpText = (TextBox)childc;
            tmpField = tmpText.ID.Split('_');
            fieldID = Convert.ToInt32(tmpField[1]);
            //save value to the database (eventually)
            debug.InnerHtml += tmpText.Text; //this just outputs the values for now
        }
    }
}

So the above should loop though all the page controls and find the textfields as added on the page_load. However, I am now wondering if it's because they don't exist. So when I save the page, it doesn't know of the controls. I can see the table control, but nothing inside it.... any ideas?!


Solution

  • Dynamic controls must be added on each page request. Preferably during the Init event. It sounds like they have not been added yet (again) by the time you iterate through your controls.

    Also, if you know your TextBoxes are within a specific control you should probably find that control first and then, using the same approach you are using, iterate over the controls. Two reasons for this are: efficiency and also, on your code, you are only searching two levels down from the page control. This may be ok but it includes other controls that will not contain any of those textboxes.