C# – Dynamically create text inputs (ASP.net/C#)

asp.netc

I have an input field on my page where the user will type in the number of text inputs they want to create. The action for the button is:

int num_flds = int.Parse(a_fld.Text);
for (int i = 0; i < num_flds; i++)
{
    TextBox tmp = new TextBox();
    tmp.ID = "answer_box" + i;
    tmp.Width = Unit.Pixel(300);
    answer_inputs.Controls.Add(tmp);
}

Now, I have another button that the user would click after they have filled in all their dynamically-created text boxes. Questions, first of all, am I creating the text boxes dynamically in the correct place? How would I get the values out of the dynamically-created text boxes? (The dynamically-created text boxes are being added to the Panel "answer_inputs".

Best Answer

I recommend reading this and a few other articles about the topic of dynamically created controls. It is not quite as straightforward as you might think. There are some important page lifecycle issues to consider.