Wednesday, March 5, 2008

How To Create TextBox Control Dynamically at Runtime




In Technique when creating control dynamically in a Page Load event

handler these controls will retain their ViewState after the

PostBack, but what if controls created dynamically at runtime in a

Button Click event handler instead of Page Load event then on

PostBack these controls ViewState are lost.To persists the

ViewState of these child controls we will recreate these controls

again on a PostBack in overrideable CreateChildControls() Method

which is called whenever

ASP.NET needs to create these WebControl in a Control Tree.

// Add TextBoxes Control to Placeholder

private void CreateTextBoxes()
  {

      for (int counter = 0; counter <= NumberOfControls; counter++)
      {
          TextBox tb = new TextBox();
          tb.Width = 150;
          tb.Height = 18;
          tb.TextMode = TextBoxMode.SingleLine;
          tb.ID = "TextBoxID" + (counter + 1).ToString();
          // add some dummy data to textboxes
          tb.Text = "Enter Title " + counter;
          phTextBoxes.Controls.Add(tb);
          phTextBoxes.Controls.Add(new LiteralControl("<br/>"));

      }

  }

In CreateTextBoxes method I loop through ‘n’ numbers of controls that we wants to create dynamically in phTextBoxes placeholder. // Create TextBoxes on PostBack.

protected override void CreateChildControls()
  {
      // Here we are recreating controls to persist the ViewState on every post back
      if (Page.IsPostBack)
      {
          NumberOfControls += 1;
          CreateTextBoxes();
      }
      else
      {
          CreateTextBoxes();
          // Increase the control value to 1
          NumberOfControls = 0;
      }

  }

CreateChildControls method, here we are recreating control on every

PostBack. If the page is created the first time we just create these

controls and save 1 in the ViewState so we know that we have created

these controls and assigned the controls id to 1.

// Increase the counter when button is clicked and add to view

state

protected void btnAddTitle_Click(object sender, EventArgs e)
  {


      NumberOfControls += 1;


  }

In button event handler we just increase the counter by 1, and save its value to ViewState for later retrieval.Once we have created these controls on ASP.NET page, retrieving data from these dynamically created controls is easy by using FindControl method. // Read TextBoxes Data
public int NumberOfControls
   {
       get
       {
           if (ViewState["Count"] == null)
           {
               return 0;
           }
           return (int)ViewState["Count"];
       }
       set
       {
           ViewState["Count"] = value++;
       }
   }

   private void ReadTextBoxes()
   {
       strValue = string.Empty;
       int n = NumberOfControls;

       for (int i = 0; i <= NumberOfControls; i++)
       {

           string boxName = "TextBoxID" + (i + 1).ToString();
           TextBox tb = phTextBoxes.FindControl(boxName) as TextBox;
           strValue += tb.Text + "\n";
        



       }
       Response.Write(strValue);


   }

23 comments:

The said...

how do i access the values in the dynamically created controls if they are added to a Table control instead of a panel holder?

santosh kumar singh said...

1.add table server control in aspx page instead of placeholder
<asp:Table ID="YourTable" runat="server" CellPadding="0" CellSpacing="0"/>

2.
add following code
TableRow FirstRow = new TableRow();
TableCell FirstCell = new TableCell();
//TextBox YourTextBox = new TextBox();
FirstCell.Controls.Add(tb);
FirstRow.Cells.Add(FirstCell);
YourTable.Rows.Add(FirstRow);

3.Read value
TextBox tb = YourTable.FindControl(boxName) as TextBox;

Vicentiu said...

Good post, thank you!

Anonymous said...

sir i am a new user. i want to create textboxes at run time (dynamically ) and save the data of textbox in database. please help me .

Dot Net Lover said...

Hi
Sorry for late reply.I have already posted the code but for you i have created a demo application please have a look and let me know


http://aspdotnetcodebook.blogspot.com/2008/12/how-to-create-textbox-control.html

Anonymous said...

hi I saw your code it is really helpfull can u tell me how to save data to database from dynamic textboxes.I have used a table in whch the data is read from database.I have used the following code to produce textboxes.

protected void Page_Load(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("select * from Categories", cnn);
SqlDataReader dr;
cnn.Open();
dr = cmd.ExecuteReader();
int i = 1;
while (dr.Read())
{
row = new TableRow();

cell = new TableCell();
label1 = new Label();
label1.Text = dr["CategoryName"].ToString();
cell.Text = label1.Text;
row.Cells.Add(cell);

cell = new TableCell();
text = new TextBox();
text.ID = "text" + i;
cell.Controls.Add(text);
row.Cells.Add(cell);

Table1.Rows.Add(row);
i++;

}
cnn.Close();
dr.Close();
}

can u help me to add data from textboxes.Thanku in advance.

Rich K said...

The example works fine for me, but in my actual code I'm using a FormView and in the CreateTextBoxes() method I have the following:

PlaceHolder phClerkships = (PlaceHolder)
FormViewProfessionalTab.FindControl("phClerkships");
phClerkships.Controls.Add(tb);
phClerkships.Controls.Add(new LiteralControl("
"));

but on the line phClerkships.Controls.Add(tb) I get an object reference not set to an instance of an object error. What am I doing wrong?

Thanks

venu manda said...

Excellent Post Yar, I searched many sites for this solution...

Anonymous said...

just i implement u r code in my project but when i am clicking submit button again one control is adding.

how to remove this bug.Please help me

Anonymous said...

thx!

Jka said...

Thanks!

Anonymous said...

Thank You... I had wanted to knw where must we declare the object for placeholder..
i.e; private placeholder phtextboxes;

sangamesh said...

Hi I have written code for dynamic generation of textboxes and label.Refer below but i am not getting textbox.text values.It shows error like
Specified argument was out of the range of valid values.Parameter name: index

Code:

protected void ddlanswers_SelectedIndexChanged(object sender, EventArgs e)
{
int count = Convert.ToInt32(ddlanswers.SelectedValue.ToString());

for (int i = 0; i < count; i++)
{
Label lbl = new Label();
TextBox txt = new TextBox();
lbl.Text = "Option " + (i + 1).ToString();
lbl.ID = "Option" + (i + 1).ToString();



txt.ID = i.ToString();
TableRow row = new TableRow();

TableCell cell = new TableCell();
cell.Controls.Add(lbl);
row.Cells.Add(cell);

TableCell cell1 = new TableCell();
cell1.Controls.Add(txt);
row.Cells.Add(cell1);

Table1.Rows.Add(row);
}
}
protected void btnsavequestion_Click(object sender, EventArgs e)
{
int count1 = Convert.ToInt32(ddlanswers.SelectedValue.ToString());
for (int i = 0; i < count1; i++)
{
TextBox tb = Table1.Rows[i].Cells[1].FindControl(i.ToString()) as TextBox;
//I m getting error here
//error:Specified argument was out of the range of valid values.Parameter name: index


}

}

BRJ said...

How can i add data to database using textbox asp control

Vedika said...

i would like to know how to add a new textbox at run time when pressed a tab key

Sivodaya Technology said...

I like your blog.....
any need in your .NET programming..
visit
www.dotnetdevelopertool.blogspot.com

ankur patel said...

Can Any one tell me how can I set the comment function like this comments?

I want the code of the comment's submit button on c# or HTML(javascript etc.)...

If any one know that then plz tell me...

My mail ID: ankur2194@gmail.com

Anonymous said...

I also want this comment box

Anonymous said...

can u help me for generate run time label and bind data from database sql at runtime...
Plz help me..

kishore said...

can u help me ..how to add context menu page in asp.net using C#.

santosh said...

@Kishore:Check out the following link

http://msdn.microsoft.com/en-us/magazine/cc163848.aspx

Anonymous said...

In a Pannel I am able to create a dynamic image control and a button control which is showing a Image and a button beside it.The image which is showing in the image control is stored in the solution explorer and the address is stored in the database.When the user click on the button the user will get to know the "Name " of the image which is stored in the database.Plz if anyone help me regarding the code.

Anonymous said...

hi i want to know how to create a labels dynamically

Post a Comment