HOW TO: Dynamically Create Controls in ASP.NET with Visual Basic .NET

Article translations Article translations
Article ID: 317515 - View products that this article applies to.
This article was previously published under Q317515
Expand all | Collapse all

On This Page

SUMMARY

This step-by-step article describes how to dynamically create controls for an ASPX Web page.

The sample project does the following:
  • It creates two TextBox controls.
  • It verifies that the TextBox contents (TextBox.text) and attributes are saved across posts to the server.
  • It describes how events that are posted by a dynamically created control are handled.

Create the Project and the Static Control

  1. In Visual Studio .NET, create a new Web project by using Visual Basic .NET. Name the project DynamicCreate.
  2. Open the WebForm1.aspx file, and then switch to HTML view. Insert the following code between the <HTML> tag and the </HTML> tag:
    <HEAD>
        <title>WebForm1</title>
        <meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.0">
        <meta name="CODE_LANGUAGE" content="Visual Basic 7.0">
        <meta name="vs_defaultClientScript" content="JavaScript">
        <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
    </HEAD>
    <body MS_POSITIONING="GridLayout">
        <form id="Form1" method="post" runat="server">
            <asp:Button id="Button1" style="Z-INDEX: 100; LEFT: 23px; POSITION: absolute; TOP: 108px" runat="server" Text="Submit" Height="27px" Width="100px"></asp:Button>
            <asp:Label id="Label4" style="Z-INDEX: 105; LEFT: 23px; POSITION: absolute; TOP: 197px" runat="server" Width="368px" EnableViewState="False"></asp:Label>
            <asp:Label id="Label3" style="Z-INDEX: 104; LEFT: 23px; POSITION: absolute; TOP: 163px" runat="server" Width="368px" EnableViewState="False"></asp:Label>
            <asp:Label id="Label2" style="Z-INDEX: 102; LEFT: 23px; POSITION: absolute; TOP: 60px" runat="server" Width="86px" Height="19px"> TextBox2:</asp:Label>
            <asp:Label id="Label1" style="Z-INDEX: 101; LEFT: 23px; POSITION: absolute; TOP: 28px" runat="server" Width="86" Height="19"> TextBox1:</asp:Label></form>
    </body>
    					
  3. Switch back to Design view to see the statically created controls that the project will use.

Create the Dynamic Control and Hook it Up

  1. In Solution Explorer, click Show All Files. The list of files that are associated with WebForm1.aspx appears. Open WebForm1.aspx.vb.
  2. Declare the TestBox controls in the .vb (code-behind) file. Also, declare a variable for the existing form element in the .aspx file. Update the declarations that follow the declaration for the WebForm1 public class:
    Public Class WebForm1
        Inherits System.Web.UI.Page
        Protected WithEvents Button1 As System.Web.UI.WebControls.Button
        Protected WithEvents Label4 As System.Web.UI.WebControls.Label
        Protected WithEvents Label3 As System.Web.UI.WebControls.Label
        Protected WithEvents Label2 As System.Web.UI.WebControls.Label
        Protected WithEvents Label1 As System.Web.UI.WebControls.Label
    
        ' Added by hand for access to the form.
        Protected Form1 As System.Web.UI.HtmlControls.HtmlForm
    
        ' Added by hand; will create instance in OnInit.
        Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox
        Protected WithEvents TextBox2 As System.Web.UI.WebControls.TextBox
    						
    The TextBox declarations are entered by hand as they would be if a TextBox were dragged from the toolbox to the ASPX page. However, in this case, you create the controls dynamically.
  3. Add code to create the TextBox controls dynamically. The controls are created every time that the page is run. The best place to do this is in the Page_Init function that the WebForm1 class provides. Locate the Page_Init function. Expand the code that is marked with the comment "Web Form Designer generated code." Modify the Page_Init functions, so that they appear similar to the following:
    Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
        ' Create dynamic controls here.
        TextBox1 = New TextBox()
        TextBox1.ID = "TextBox1"
        TextBox1.Style("Position") = "Absolute"
        TextBox1.Style("Top") = "25px"
        TextBox1.Style("Left") = "100px"
        Form1.Controls.Add(TextBox1)
    
        TextBox2 = New TextBox()
        TextBox2.ID = "TextBox2"
        TextBox2.Style("Position") = "Absolute"
        TextBox2.Style("Top") = "60px"
        TextBox2.Style("Left") = "100px"
        Form1.Controls.Add(TextBox2)
    
        ' CODEGEN: The Web Form Designer requires this method call.
        ' Do not modify it by using the code editor.
        InitializeComponent()
    End Sub
    						
    This code dynamically creates two TextBox controls, sets their IDs and positions, and then binds them to the Form Controls collection. You can also add Web Forms Panel controls to the ASPX page, and then bind the text boxes to those controls in the Page_Init function, as in the following example:
        TextBox1 = New TextBox()
        TextBox1.ID = "TextBox1"
    ' comment   add command  the Form Controls collection as follows
    '   Form1.Controls.Add(TextBox1)'
        Panel1.Controls.Add(TextBox1)
    					
    Note When you create dynamic controls on a Web Form, you must create the controls and add them to the controls collection in either the Page_Init event handler or the Page_Load event handler. Otherwise, the controls may not behave as expected.
  4. Initialize the Text property for the text boxes. Modify the existing Page_Load function:
    Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        If Not IsPostBack Then
            ' Set the initial properties for the text boxes.
            TextBox1.Text = "TextBox1"
            TextBox2.Text = "TextBox2"
        End If
    End Sub
    						
    You must set the initial value (If Not IsPostBack) of the text boxes only one time. The IPostBackDataHandler interface for the text boxes maintains this information. You do not have to reset the value for later posts.
  5. Provide a handler for the TextBox TextChanged events. Add the following code after the Page_Load function:
    Private Sub TextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged, TextBox2.TextChanged
        Dim txtBoxSender As TextBox
        Dim strTextBoxID As String
    
        txtBoxSender = CType(sender, TextBox)
        strTextBoxID = txtBoxSender.ID
    
        Select Case strTextBoxID
            Case "TextBox1"
                Label3.Text = "TextBox1 text was changed"
    
            Case "TextBox2"
                Label4.Text = "TextBox2 text was changed"
        End Select
    End Sub
    						
    This code verifies which control triggered the event, and then reports this to the user by using the appropriate Label control. Notice that this function handles the TextChanged event for both of the dynamically created TextBox controls. By default, AutoPostBack is false for the TextBox controls. Therefore, if a user changes the text in the controls, this action does not cause a PostBack to the server. However, when the user clicks Submit to post the form to the server, this action triggers the TextChanged events for the TextBox controls, and then this function is called.

Save, Build, and Then Run the Sample

Save, and then build the sample. To run the sample in Visual Studio .NET, right-click the ASPX file, and then click View in Browser.

Properties

Article ID: 317515 - Last Review: February 11, 2004 - Revision: 4.4
APPLIES TO
  • Microsoft ASP.NET 1.0
  • Microsoft Visual Basic .NET 2002 Standard Edition
  • Microsoft ASP.NET 1.1
  • Microsoft Visual Basic .NET 2003 Standard Edition
Keywords: 
kbctrlcreate kbevent kbhowtomaster kbservercontrols kbwebforms KB317515

Give Feedback

 

Contact us for more help

Contact us for more help
Connect with Answer Desk for expert help.
Get more support from smallbusiness.support.microsoft.com