467,877 Members | 1,283 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Share your developer knowledge by writing an article on Bytes.

How To: Use Dynamic Controls in ASP.NET

Expert Mod 8TB
Sometimes, when developing web applications, we need to be able to dynamically load controls based on user selections. The following article describes a simple scenario where TextBox controls need to be dynamically loaded according to user input. This simple example can be further extended to dynamically load custom web user controls.

Please familiarize yourself with the ASP.NET Page Life Cycle. It is crucial to understand this cycle in order to avoid messy problems.

The Scenario
Provide the user with a DropDownList in order to let them select the number of TextBoxes to display. Retrieve the values entered by the user and display them in a sentence.

A Dynamic Solution
First of all we need to allocate enough space for the TextBoxes.
For this example I am going to use an array of TextBoxes, in your project you can create as many controls as you require dynamically from a database etc.

Expand|Select|Wrap|Line Numbers
  1. private TextBox textBoxArr(5) 
Expand|Select|Wrap|Line Numbers
  1. Private textBoxArr(4) As TextBox
Now, we have declared an array of 5 TextBoxes but before we can use these TextBoxes we have to instantiate them (create instances of them). We do this in the Page_Init method.

The reason we do this in the Page_Init method is because this method occurs before ASP.NET loads the page's ViewState. Recall that the ViewState contains all of the page's Objects' properties. ASP.NET sets the properties of your objects right after the Page_Init method finishes executing. If you have not instantiated your TextBoxes (controls) at this point, they will not contain any properties (including the Text property that we're interested in).

Expand|Select|Wrap|Line Numbers
  1. private void Page_Init(Objectsender, System.EventArgs e) 
  2. {
  3.     //This event happens before any controls are initialized by ASP.NET
  4.     //The ViewState for objects has not been loaded.
  5.     //After this event happens, the ViewState is loaded for each control and the object's properties are filled with the values submitted.
  7.     //Creating the TextBox Objects that are dynamically shown in the web page
  8.     //according to the number selected from a DropDownList
  9.         for(int i = 0; i < textBoxArr.Length - 1; i++)
  10.         {   textBoxArr(x) = New TextBox();
  11.             textBoxArr(x).ID = "myTextBox" + x.ToString();
  12.             textBoxArr(x).Visible = False; //Initializing the TextBox so that it is not rendered in the browser 
  13.             Pnl_TextBoxes.Controls.Add(textBoxArr(x)); //Adding the TextBox to the Panel that holds the text boxes.
  14.         }
  16. }
Expand|Select|Wrap|Line Numbers
  1. Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
  2.     'This event happens before any controls are initialized by ASP.NET'
  3.     'The ViewState for objects has not been loaded.'
  4.     'After this event happens, the ViewState is loaded for each control and the object's properties are filled with the values submitted.'
  6.     'Creating the TextBox Objects that are dynamically shown in the web page'
  7.     'according to the number selected from a DropDownList'
  8.         For x As Integer = 0 To textBoxArr.Length - 1
  9.             textBoxArr(x) = New TextBox
  10.             textBoxArr(x).ID = "myTextBox" + x.ToString
  11.             textBoxArr(x).Visible = False 'Initializing the TextBox so that it is not rendered in the browser 
  12.             Pnl_TextBoxes.Controls.Add(textBoxArr(x)) 'Adding the TextBox to the Panel that holds the text boxes.
  13.         Next
  15. End Sub
Remember that you must add your dynamically created controls to the page in order to display and use them. In this example we are adding the controls to a panel which is already part of the page.

So, now user is able to choose to use up to 6 TextBoxes and we are able to retrieve the Text values that the user has entered into these TextBoxes.

The following code displays the number of TextBoxes that the user has selected from a DropDownList named "numTextBoxes":

Expand|Select|Wrap|Line Numbers
  1. private numTextBoxes_SelectedIndexChanged(System.Objectsender, System.EventArgs e) 
  2. {
  3.         For(int i= 0; i < numTextBoxes.SelectedValue - 1; i++)
  4.         {
  5.             textBoxArr(x).Visible = True //Setting the TextBox visible property to True
  6.         }
  7. }
Expand|Select|Wrap|Line Numbers
  1. Protected Sub numTextBoxes_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles numTextBoxes.SelectedIndexChanged
  2.         For x As Integer = 0 To numTextBoxes.SelectedValue - 1
  3.             textBoxArr(x).Visible = True 'Setting the TextBox Visible property to True'
  4.         Next
  5. End Sub
The following code is an example of how to retrieve the text values from the dynamically created TextBoxes. The method in this example displays the text retrieved from the TextBoxes in a label named lbl_message.

Expand|Select|Wrap|Line Numbers
  1. private void btnText_Click(Object sender, System.EventArgs e) 
  2. {
  3.         StringBuilder str = New System.Text.StringBuilder();
  5.         for(int i = 0;i < textBoxArr.Length - 1)
  6.         {
  7.             If (textBoxArr(i)!= null)
  8.             {
  9.                 str.Append(" " + textBoxArr(i).Text); //Grabbing the text from the TextBox...remember that at this stage the TextBox's Text property has already been set by ASP.NET according to its ViewState
  10.             }
  11.         }
  13.         //Showing in a label what was in the TextBoxes
  14.         lbl_message.Text = "message: " + str.ToString();
  15.     }
Expand|Select|Wrap|Line Numbers
  1. Private Sub btnText_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnText.Click
  3.         Dim str As New StringBuilder
  5.         For i As Integer = 0 To textBoxArr.Length - 1
  6.             If textBoxArr(i) IsNot Nothing Then
  7.                 str.Append(" " + textBoxArr(i).Text) 'Grabbing the text from the TextBox...remember that at this stage the TextBox's Text property has already been set by ASP.NET according to its ViewState
  8.             End If
  9.         Next
  11.     'Showing in a label what was in the TextBoxes
  12.         lbl_message.Text = "message: " + str.ToString
  13.      End Sub

A Dynamic Solution Using Custom Web User Controls

When dynamically loading a Web User Control into your page you must register that control with your page. In order to do that ASP.NET has provided us with the Page.LoadControl() method.

Example of using custom Web User Controls:
Expand|Select|Wrap|Line Numbers
  1. Private WithEvents myCtrl As MyWebUserControl
  3. Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
  4.     myCtrl = Page.LoadControl("~/MyWebUserControl.ascx")
  5.     Pnl_ForDisplayingMyControl.Controls.Add(myCtrl)
  6. End Sub
You must load the control in the Page_Init() method otherwise your web user control's ViewState will not be loaded properly and you won't be able to use it.
Dec 18 '07 #1
  • viewed: 50229
actually i am working with c# . i am not able to understand the vb code.
so please help me .
Sep 18 '08 #2
please help me out in firing linkbutton click event in itemtemplate of datalist. i am only using C# (.cs) file. i am creating itemplate and every thing dynamically. i am able to display what i want. but the linkbuttons which i am displaying are not firing click event.
please give me solution. if possible you can mail me the solution to <snipped: email removed>

Apr 21 '09 #3
Expert Mod 8TB
Hi Raj, your question is being answered in this thread.

Please do not post your email address. This is for your own safety.
Apr 21 '09 #4
This was for use in a User Control, not the page itself. User Controls do not load as a page, but could be referenced in code-behind as an HtmlForm. I actually found an easier way than to append to the aspnetForm object, though.

I put an ASP panel on my main page (ASPX file), and in the Page_Init, dynamically loaded my User Control to it with code like you have above:

Expand|Select|Wrap|Line Numbers
  1. myCtrl = Page.LoadControl("~/MyWebUserControl.ascx") 
  2. Pnl_ForDisplayingMyControl.Controls.Add(myCtrl)
I then added a panel into the User Control (ASCX file) ASP markup. Then, in the Page_Init of the User Control code-behind, I dynamically loaded the dropdown I was trying to load into that User Control panel (instead of adding it to the HtmlForm, which I still think should have worked) using something similar to this (don't have the code in front of me right now):

Expand|Select|Wrap|Line Numbers
  1. DropDownList myDDL = new DropDownList();
  2. myDDL.Items.Add(new ListItem(myText, myVal);
  3. pnlInUserControl.Controls.Add(myDDL);
The problem I was trying to solve was that the dropdown would not dynamically load onto the page itself, for some reason. So I did it in a User Control, then loaded the User Control onto the main page. Quite a workaround, but it did the trick. I don't know why I needed to do it, though, but the dropdown would never appear on the page and kept getting "Object reference not set to an instance of an object" errors, though I was trying to add it to the main page's panel the same exact way as I did in the User Control. Made no sense to me except for the separation of code that User Controls allow (they run in their own "space"). Even so, I still don't get why I had to do the workaround. Any ideas?

Mar 6 '12 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

1 post views Thread by Will | last post: by
1 post views Thread by hybrid | last post: by
2 posts views Thread by Dave Williamson | last post: by
3 posts views Thread by Leo J. Hart IV | last post: by
3 posts views Thread by WebBuilder451 | last post: by
1 post views Thread by Diffident | last post: by
9 posts views Thread by Tarscher | last post: by
reply views Thread by jack112 | last post: by
reply views Thread by MrMoon | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.