472,800 Members | 1,289 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 472,800 developers and data experts.

How To: Use Dynamic Controls in ASP.NET

9,735 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
4 51365
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
9,735 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

by: Will | last post by:
Hi all. I'm learning VB.Net and am developing a WinForms app. I'm trying to make an app that I will use to scan in one or more than on image. I want to use a tabbed interface to hold each image....
by: theComputer7 | last post by:
I cut down the code to make this half way understandable... I have read Data Grid girls caution about over use of dynamic controls. I truly believe what I am doing requires dynamically inserted...
by: hybrid | last post by:
I have problems in understanding the behavior of the events triggered by dynamically created controls over a webform. Could you help me? In a webform, I have a static PlaceHolder PH containing...
by: Dave Williamson | last post by:
When a ASPX page is created with dynamic controls based on what the user is doing the programmer must recreate the dynamic controls again on PostBack in the Page_Load so that it's events are wired...
by: Leo J. Hart IV | last post by:
OK, here's another question for the experts: I am building a multi-step (3 steps actually) form using a panel for each step and hiding/displaying the appropriate panel/panels depending on which...
by: mytestemailaccount | last post by:
Hi, Hope you can help. I am relatively new to all this but would appreciate the groups help. The scenario: I am c# and asp.net to create a web application. The web page contains a user...
by: pbb | last post by:
I'm creating a set of dynamic controls on a webpage by calling my BuildControls sub in the Page_Init sub. I recreate the controls by calling the BuildControls sub in the LoadViewState override...
by: WebBuilder451 | last post by:
I have a series of dynamic link buttons created based upon a datareader. I've added a click event and it calls the sub ok: example: "while loop through the reader" Dim ltrCtrl As New...
by: Diffident | last post by:
Hello All, I am trying to add dynamic controls onto my page and here is how I am doing that. I have a page which has a button called as "AddMoreControls" and in this button's event handler I...
by: Tarscher | last post by:
hi all, I have this seemingly simple problem. I have lost a lot of time on it though. When a user selects a value from a dropdownlist (static control) a dynamic control is generated. I have...
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
by: erikbower65 | last post by:
Here's a concise step-by-step guide for manually installing IntelliJ IDEA: 1. Download: Visit the official JetBrains website and download the IntelliJ IDEA Community or Ultimate edition based on...
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
by: DJRhino | last post by:
Private Sub CboDrawingID_BeforeUpdate(Cancel As Integer) If = 310029923 Or 310030138 Or 310030152 Or 310030346 Or 310030348 Or _ 310030356 Or 310030359 Or 310030362 Or...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: Mushico | last post by:
How to calculate date of retirement from date of birth
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.