Wednesday, November 9, 2011

How to access values of dynamically created TextBoxes


If one adds controls dynamically to a page and wants to get their information after PostBack, one needs to recreate these elements after the PostBack. Let's consider the following idea: First you create some controls:
   for(int i=0;i<10;i++) {
      TextBox objBox = new TextBox();
      objBox.ID = "objBox" + i.ToString();
      this.Page.Controls.Add(objBox);
   }
After PostBack, you want to retrieve the text entered in the third TextBox. If you try this:
   String strText = objBox2.Text;
you'll receive an exception. Why? Because the boxes have not been created again and the local variable objBox2 simply not exists.
How to retrieve the Box?
You'll need to recreate the box by using the code above. Then, you may try to get its value by using the following code:
   TextBox objBox2;
   objBox2 = this.Page.FindControl("objBox2") as TextBox;
   if(objBox2 != null)
      Response.Write(objBox2.Text);