473,387 Members | 1,890 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,387 developers and data experts.

How To: Use Dynamic Controls in ASP.NET

Frinavale
9,735 Expert Mod 8TB
Introduction
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.

Background
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.

(C#)
Expand|Select|Wrap|Line Numbers
  1. private TextBox textBoxArr(5) 
  2.  
(VB.NET)
Expand|Select|Wrap|Line Numbers
  1. Private textBoxArr(4) As TextBox
  2.  
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).

(C#)
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.
  6.  
  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.         }
  15.  
  16. }
  17.  
(VB.NET)
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.'
  5.  
  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
  14.  
  15. End Sub
  16.  
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":

(C#)
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. }
  8.  
(VB.NET)
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
  6.  
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.

(C#)
Expand|Select|Wrap|Line Numbers
  1. private void btnText_Click(Object sender, System.EventArgs e) 
  2. {
  3.         StringBuilder str = New System.Text.StringBuilder();
  4.  
  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.         }
  12.  
  13.         //Showing in a label what was in the TextBoxes
  14.         lbl_message.Text = "message: " + str.ToString();
  15.     }
  16.  
(VB.NET)
Expand|Select|Wrap|Line Numbers
  1. Private Sub btnText_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnText.Click
  2.  
  3.         Dim str As New StringBuilder
  4.  
  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
  10.  
  11.     'Showing in a label what was in the TextBoxes
  12.         lbl_message.Text = "message: " + str.ToString
  13.      End Sub
  14.  

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
  2.  
  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
  7.  
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 51561
actually i am working with c# . i am not able to understand the vb code.
so please help me .
Sep 18 '08 #2
hi
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>

Thanks
Apr 21 '09 #3
Frinavale
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?

-Tom
Mar 6 '12 #5

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

Similar topics

1
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....
2
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...
1
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...
2
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...
3
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...
5
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...
1
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...
3
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...
1
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...
9
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.