Dynamically creating ASP.NET controls 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. But sometimes we may need to generate ASP.NET controls in the server side using the VB.NET or C# code. For example, consider a case where you are developing an application where you want to display a list of checkboxes to the user, depending on the number of records in a database table. In this case, you cannot drag and drop few checkbox controls, because you will not know how many checkboxes you are going to need until you retrieve the records from the database.
In this article, I will discuss how you can create ASP.NET controls at runtime using C# syntax. You can easily convert this to VB.NET syntax with little effort. Create a new ASP.NET web application using Visual Studio.NET. It will create a sample web page with the name webform1.aspx. Let us use this page for our experimentation. Drag and drop a panel control into the webform. We will dynamically generate a checkbox and add to this panel.
Double click on the webform1.aspx page. This will add a page load event handler in the code behind file. Add few lines of code in the Page_Load event handler as shown below:
private void Page_Load(object sender, System.EventArgs e) { CheckBox _checkbox = new CheckBox(); _checkbox.ID = "chkDynamicCheckBox"; _checkbox.Text = "This is a dynamically generated checkbox"; Panel1.Controls.Add (_checkbox); }
The above code will create a checkbox dynamically and add to the panel in the form. Using this approach, you can create any other ASP.NET control during runtime and add to the form.
How to specify a position for the dynamically dynamically created ASP.NET control? The most common method is to use <table> to position controls and text in html. In our case, since we are dynamically generating the controls, we may want to use ASP.NET table control to dynamically create rows and cells in the table and add our dynamic controls into it. Drag and drop an ASP.NET table control into the form and give it the name 'tblDynamic'. Now, go back to the Page_Load event handler in the code behind file. 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.
private void Page_Load(object sender, System.EventArgs e) { 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); } }
How to access the dynamically created ASP.NET controls? If we drag and drop controls to the web form, the designer automatically generates some code in the aspx page, gives an id to the control and creates the required declarations in the code behind file. This allows us to easily access the control from code behind file and set/get any of it's properties.
But what will happen to the controls created during runtime? How can we access it's properties?
The easiest way to access these dynamically created textboxes is, iterate through all controls in the form and check if it is textbox. In the above example, we have prefixed the ID with "txt_" and then appended the serial number to it for all dynamically generated controls.
Use the following recursive function to iterate through the list of all controls in the form. We are passing the form itself as parameter to the the function. The function will iterate through all children of the passed control and checks if the child control is a textbox and if the id starts with "txt_". If it matches, it sets the Text property to "You Got It!"
void IterateControls(Control parent) { foreach (Control child in parent.Controls) { if (child.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox") && child.ID.IndexOf("txt_") == 0) { TextBox textbox = (TextBox)child; textbox.Text = "You Got It !"; } if (child.Controls.Count > 0) { IterateControls(child); } } }
How to test it? Add the above method to your code behind file. Drag and drop a button control to the form and double click on it to create a button clicked event handler. Call the above method from the button click event handler as shown below:
IterateControls(this);
Now, run the application and see. When you launch the application, it will dynamically create 5 textboxes and when you click on the button, it will populate the value 'You Got It !" in all the dynamically created textboxe controls.
|
| Author: pappu 17 Dec 2004 | Member Level: Bronze Points : 0 |
It is one of the best Articles for freshers....
|
| Author: Geetha Gopi 16 Jan 2005 | Member Level: Bronze Points : 0 |
Hi, I am trying to convert this to vb.net. I am having a doubt in the IterateControls function. the parameter parent, where i have to declare that and what data type is it. I am a beginner for .net. please help me.
|
| Author: Tony John 17 Jan 2005 | Member Level: Gold Points : 0 |
The parameter 'parent' is of type 'Control'. In VB.NET you can declare it as
private sub IterateControls(ByVal parent as Control) --- end sub
|
| Author: Siddesh Kapadi 15 Apr 2005 | Member Level: Bronze Points : 0 |
this code doesnot work as the values dont get displayed in my textboxes.
|
| Author: anupam thakur 09 May 2005 | Member Level: Bronze Points : 0 |
i tries all this but i'm unable to get values which i enter at run time from the text boxes also when i press some button the dynamically generated controls are lost
|
| Author: Natarajan.M 22 May 2005 | Member Level: Gold Points : 0 |
This is very much helpful to create a controls at runtime.Code is working fine
|
| Author: navinkumar 27 May 2005 | Member Level: Bronze Points : 0 |
I love this article.
Thankyou.
|
| Author: Kevin Wison 24 Aug 2005 | Member Level: Silver Points : 0 |
This is an excellent article for a novice. Keep it up!
|
| Author: Besnik Shehu 25 Nov 2005 | Member Level: Bronze Points : 0 |
I have a page that uses the above code, but I'm running into problems.
It works like this. The user is asked how many names they need to submit, and then two textboxes are created dynamically based on the number the user chooses.
The problem is that on postback those controls are lost, and the information typed on the controls is lost. How do I prevent that what happening, and how can I retrieve the data on Postback, that was entered on the dynamically created controls?
Thanks
|
| Author: mallika 04 Jun 2007 | Member Level: Bronze Points : 0 |
its coming out of the For loop..Not working
|
| Author: nitin 23 Jun 2007 | Member Level: Silver Points : 0 |
No doubt ur code is working properly but if i want to place textbox only in both cell then textbox willhave same ID ? pls mail me the ans
|
| Author: guruank 07 Aug 2007 | Member Level: Bronze Points : 0 |
I am having problems with accessing the created controls when i try to access them them they post back and the page becomes blank once again..
plzzzzzz help
|
| Author: Pavan B 18 Feb 2008 | Member Level: Silver Points : 0 |
The code works for the first time. Suppose we have to create 4 text boxes repeatedly. The code works only for the first time. We can't create the 4 textboxes repeatedly. Also not possible to resize the textboxes.
|
| Author: DaRocker22 26 May 2008 | Member Level: Bronze Points : 2 |
Put your code in OnInit instead of Page load so you when you do a postback the controls don't get rebuilt and set back to the default values and lose the postback data.
protected override void OnInit(System.EventArgs e) { // Dynamic code goes here }
|