How To: Use Dynamic Controls in ASP.NET

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    How To: Use Dynamic Controls in ASP.NET

    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#)
    Code:
    private TextBox textBoxArr(5)
    (VB.NET)
    Code:
    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).

    (C#)
    Code:
    private void Page_Init(Objectsender, System.EventArgs e) 
    {
        //This event happens before any controls are initialized by ASP.NET
        //The ViewState for objects has not been loaded.
        //After this event happens, the ViewState is loaded for each control and the object's properties are filled with the values submitted.
    
        //Creating the TextBox Objects that are dynamically shown in the web page
        //according to the number selected from a DropDownList
            for(int i = 0; i < textBoxArr.Length - 1; i++)
            {   textBoxArr(x) = New TextBox();
                textBoxArr(x).ID = "myTextBox" + x.ToString();
                textBoxArr(x).Visible = False; //Initializing the TextBox so that it is not rendered in the browser 
                Pnl_TextBoxes.Controls.Add(textBoxArr(x)); //Adding the TextBox to the Panel that holds the text boxes.
            }
    
    }
    (VB.NET)
    Code:
    Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        'This event happens before any controls are initialized by ASP.NET'
        'The ViewState for objects has not been loaded.'
        'After this event happens, the ViewState is loaded for each control and the object's properties are filled with the values submitted.'
    
        'Creating the TextBox Objects that are dynamically shown in the web page'
        'according to the number selected from a DropDownList'
            For x As Integer = 0 To textBoxArr.Length - 1
                textBoxArr(x) = New TextBox
                textBoxArr(x).ID = "myTextBox" + x.ToString
                textBoxArr(x).Visible = False 'Initializing the TextBox so that it is not rendered in the browser 
                Pnl_TextBoxes.Controls.Add(textBoxArr(x)) 'Adding the TextBox to the Panel that holds the text boxes.
            Next
    
    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 "numTextBox es":

    (C#)
    Code:
    private numTextBoxes_SelectedIndexChanged(System.Objectsender, System.EventArgs e) 
    {
            For(int i= 0; i < numTextBoxes.SelectedValue - 1; i++)
            {
                textBoxArr(x).Visible = True //Setting the TextBox visible property to True
            }
    }
    (VB.NET)
    Code:
    Protected Sub numTextBoxes_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles numTextBoxes.SelectedIndexChanged
            For x As Integer = 0 To numTextBoxes.SelectedValue - 1
                textBoxArr(x).Visible = True 'Setting the TextBox Visible property to True'
            Next
    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.

    (C#)
    Code:
    private void btnText_Click(Object sender, System.EventArgs e) 
    {
            StringBuilder str = New System.Text.StringBuilder();
    
            for(int i = 0;i < textBoxArr.Length - 1)
            {
                If (textBoxArr(i)!= null)
                {
                    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
                }
            }
    
            //Showing in a label what was in the TextBoxes
            lbl_message.Text = "message: " + str.ToString();
        }
    (VB.NET)
    Code:
    Private Sub btnText_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnText.Click
    
            Dim str As New StringBuilder
    
            For i As Integer = 0 To textBoxArr.Length - 1
                If textBoxArr(i) IsNot Nothing Then
                    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
                End If
            Next
    
        'Showing in a label what was in the TextBoxes
            lbl_message.Text = "message: " + str.ToString
         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.LoadContro l() method.

    Example of using custom Web User Controls:
    [code=vbnet]
    Private WithEvents myCtrl As MyWebUserContro l

    Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArg s) Handles Me.Init
    myCtrl = Page.LoadContro l("~/MyWebUserContro l.ascx")
    Pnl_ForDisplayi ngMyControl.Con trols.Add(myCtr l)
    End Sub
    [/code]

    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.
    Last edited by Frinavale; Jun 28 '10, 04:38 PM. Reason: Addec C#
  • smithak82
    New Member
    • Sep 2008
    • 12

    #2
    actually i am working with c# . i am not able to understand the vb code.
    so please help me .

    Comment

    • rajkumarbathula
      New Member
      • Aug 2008
      • 18

      #3
      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
      Last edited by Frinavale; Apr 21 '09, 04:32 PM. Reason: removed email address

      Comment

      • Frinavale
        Recognized Expert Expert
        • Oct 2006
        • 9749

        #4
        Hi Raj, your question is being answered in this thread.

        Please do not post your email address. This is for your own safety.

        Comment

        • navyjax2
          New Member
          • Aug 2007
          • 18

          #5
          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:

          Code:
          myCtrl = Page.LoadControl("~/MyWebUserControl.ascx") 
          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):

          Code:
          DropDownList myDDL = new DropDownList();
          myDDL.Items.Add(new ListItem(myText, myVal);
          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

          Comment

          Working...