tags:

views:

1060

answers:

2

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".

+2  A: 

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.

BobbyShaftoe
+1  A: 

When creating web controls dynamically, I find it best to have the controls themselves report in the answers. You can achieve it like this:

Create something in your Page class to store the values:

private readonly Dictionary<TextBox, string> values=new Dictionary<TextBox, string>();

Make a method to act as a callback for the textboxes when their value changes:

void tmp_TextChanged(object sender, EventArgs e)
    {
        TextBox txt = sender as TextBox;
        if(txt!=null)
        {
            values.Add(txt,txt.Text);
        }
    }

And then add this method to each textbox as they are added:

int num_flds;
    if(!int.TryParse(a_fld.Text,out num_flds))
    {
        num_flds = 0;
    }
    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);
            tmp.TextChanged += tmp_TextChanged;
    }

Finally, you iterate through the dictionary on callback to see if it holds any values. Do this in the OnPreRender method for instance.

Edit: There is a problem with this, if the number of text fields are decreased on postback. Some safe way to recreate the previous textfields on postback should be employed.

Øyvind Skaar