How To Create Controls Dynamicaly in ASP.NET

ASP.NET is a very powerful and flexible technology, allowing programmers to develop sophisticated web applications within a short period of time. It is so easy to drag and drop controls in a web form and start writing the business logic in the code behind file. Ofcourse, dragging and dropping controls from the toolbox is the easiest approach. In this article, I will discuss how you can create ASP.NET controls at runtime using C# syntax. 1. Create a new ASP.NET web application using VS.NET 2. Drag a Drop a Panel control into webform 3. Double click on the webpage this will add a Load Event Handler in the code behind private void Page_Load(object sender, System.EventArgs e) { TextBox _txt = new TextBox(); _txt.ID = "txtId"; _txt.Text = "This is Dynamicaly genrated Textbox"; Panel1.Controls.Add(_txt); } The above code will create a TextBox dynamicaly and add to the form.Using this approach you can create any other ASP.NET server controls and add to form. How To Specify postion for dynamicaly created control The most common method is to use Table control to position controls and text in Page. The following code sample will create 5 textboxes and labels. We will create 5 rows and 2 cells in each row dynamically and add our dynamicaly created textbox/label controls to the table so that they will be aligned properly and will appear in the page in proper format. protected void Page_Load(object sender, EventArgs e) { Table tblDynamic = new Table(); for (int i = 0; i < 5; i++) { TableRow tr = new TableRow(); // Create column 1 TableCell td1 = new TableCell(); // Create a label control dynamically Label _label = new Label(); _label.ID = "lbl" + i.ToString(); _label.Text = "Enter Value " + i.ToString(); // Add control to the table cell td1.Controls.Add(_label); // Create column 2 TableCell td2 = new TableCell(); TextBox _text = new TextBox(); _text.ID = "txt_" + i.ToString(); // Add control to the table cell td2.Controls.Add(_text); // Add cell to the row tr.Cells.Add(td1); tr.Cells.Add(td2); // Add row to the table. tblDynamic.Rows.Add(tr); } pnl.Controls.Add(tblDynamic); }


Post a Comment


Close Menu