How do I get the value of the dynamically created TextBox?

2

I have a form that receives an amount of TextBox that should be instantiated, the page then generates the textboxes, however I do not know how I can get the values.

hd = Request.QueryString["qtHD"];
mem = Request.QueryString["qtMem"];
hdnum = Convert.ToInt16(hd);

while (hdnum >= 1)
{
    text1 = new TextBox();
    String txtBox = "txtTamHD" + hdnum.ToString();
    text1.ID = txtBox;
    form1.Controls.Add(text1);
    hdnum--;
}
    
asked by anonymous 27.02.2014 / 19:40

3 answers

1

In WebForms, for the dynamically created control values to be retrieved, you must ensure that all controls are created and added to the page hierarchy before the ProcessPostData event.

After this event in the page lifecycle, you should no longer change the page's control hierarchy, at least as far as controls that post data are concerned.

In google images have good references on page life cycle ... in fact, it was all this complexity that motivated me to switch to ASP. NET MVC.

EDIT 2 Page lifecycle image

link

EDIT 3

To intercept the Init event of the page, go to the code of the page and do so:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);

    // ... seu código de criação dos controles dinâmicos aqui
}
    
27.02.2014 / 19:47
2

As @MiguelAngelo commented, the catch is in the page lifecycle . Dynamic controls must be recreated in the Page_Init step so that there is before the viewstate load. This means that somehow , you should save as many text boxes as you have created to re-create them, using the same ID .

Tip:

  • Create an attribute of type List<TextBox> (let's call CamposDinamicos )

  • Write a method that gets everything it needs to create the text boxes. It should not access anything outside of it, just get its arguments and create the TextBoxes in CamposDinamicos . The minimum he should receive is the number of fields.

  • Call this method on Page_Init . The arguments for it may have to be retrieved from Session .

  • When you need to access the value of the dynamic fields, look for them in the CamposDinamicos and not FindControls()

  • This is a translated version of the original answer I posted at link .

        
    27.02.2014 / 20:37
    0

    Oops!

    So ..

    You can do a% of Controls .. Type this: foreach Then you can sweep all the controls on your form. Make a foreach (Control controle in this.Controls) { } to see if it's a TextBox and that's it! ;)

    Did you help?

        
    27.02.2014 / 19:47