Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

HOW TO: Dynamically Create Controls in ASP.NET by Using Visual C# .NET


View products that this article applies to.

Summary

Use this step-by-step guide to dynamically create controls for an .aspx page.

This article demonstrates how to dynamically create a control for an .aspx page. The sample project does the following:
  • Creates two TextBox controls.
  • Verifies that the contents (TextBox.text) and the attributes of the TextBox are saved across posts to the server.
  • Illustrates handling events that are posted by a dynamically-created control.

Create the Project and Static Control

  1. Start Microsoft Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. Click Visual C# Projects under Project Type, and then click ASP.NET Web Application under Templates. Name the project DynamicCreate.
  4. Open the WebForm1.aspx file, and switch to HTML view. Replace the existing code between the <HTML> and </HTML> tags with the following code:
    <HEAD>
        <title>WebForm1</title>
        <meta content="Microsoft Visual Studio 7.0" name="GENERATOR">
        <meta content="C#" name="CODE_LANGUAGE">
        <meta content="JavaScript" name="vs_defaultClientScript">
        <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
    </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>
  5. Return 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 to display a list of the files that are associated with WebForm1.aspx. Open the WebForm1.aspx.cs file.
  2. Declare the TextBox controls in the .cs (code-behind) file. Also, declare a variable for the existing form element in the .aspx file. Update the declarations following the declaration for the WebForm1 class:
    public class WebForm1 : System.Web.UI.Page
    {
    	protected System.Web.UI.WebControls.Label Label1;
    	protected System.Web.UI.WebControls.Label Label2;
    	protected System.Web.UI.WebControls.Label Label3;
    	protected System.Web.UI.WebControls.Label Label4;
    	protected System.Web.UI.WebControls.Button Button1;
    
    	// Added by hand for access to the form.
    	protected System.Web.UI.HtmlControls.HtmlForm Form1;
    	
    	// Added by hand; will create instance in OnInit.
    	protected System.Web.UI.WebControls.TextBox TextBox1;
    	protected System.Web.UI.WebControls.TextBox TextBox2;
    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 OnInit function that the WebForm1 class provides.

    Locate the OnInit function. Expand the code that is marked with the "Web Form Designer generated code" comment. Modify the OnInit function so that it looks similar to the following code:
    override protected void OnInit(EventArgs e)
    {
        // Create dynamic controls here.
        // Use "using System.Web.UI.WebControls;"
        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);
    
        this.TextBox1.TextChanged += new System.EventHandler(this.TextBox_TextChanged);
        this.TextBox2.TextChanged += new System.EventHandler(this.TextBox_TextChanged);
    
        // 
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        // 
        InitializeComponent();
        base.OnInit(e);
    }
    This code dynamically creates two TextBox controls, sets their IDs and positions, and then binds them to the Form Controls collection. The code also wires up the TextChanged events of the text boxes to a handler (TextBox_TextChanged).

    Other than setting the TextBox position programmatically and binding it to the Form Controls collection, you can add Web Forms Panel controls to the .aspx page and bind the text boxes to those in the OnInit function, similar to this:
    TextBox1 = new TextBox();
        TextBox1.ID = "TextBox1";
    //Form1.Controls.Add(TextBox1);
        Panel1.Controls.Add(TextBox1);
    Note When you create dynamic controls on a Web Form, the controls must be created and added to the controls collection either in the OnInit or in the Page_Load events. Otherwise, the controls behave unexpectedly.
  4. Initialize the Text property and styles for the text boxes. Modify the existing Page_Load function as follows:
    private void Page_Load(object sender, System.EventArgs e)
    {
        if(!IsPostBack)
        {
            // Set the initial properties for the text boxes.
            TextBox1.Text = "TextBox1";
            TextBox2.Text = "TextBox2";
        }
    }
    The initial value of the text boxes (if(!IsPostBack)) is set one time. This information is maintained by the IPostBackDataHandler interface for the text boxes, making it unecessary to reset the value for subsequent posts.
  5. Provide a handler for the TextChanged events of the TextBox control. Add the following code after the Page_Load function body:
    private void TextBox_TextChanged(object sender, System.EventArgs e)
    {
        TextBox txtBoxSender = (TextBox)sender;
        string strTextBoxID = txtBoxSender.ID;
    
        switch(strTextBoxID)
        {
            case "TextBox1":
                Label3.Text = "TextBox1 text was changed";
                break;
            case "TextBox2":
                Label4.Text = "TextBox2 text was changed";
                break;
        }
    }
    This code checks to see which control triggered the event and then reports this to the user by using the approprite 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, changing the text in the controls does not cause a PostBack to the server. However, when the Submit button is clicked to post the form to the server, the TextChanged events for the TextBox controls are triggered, and this function is called.

Save, Build, and Run the Sample

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

↑ Back to the top


Keywords: KB317794, kbwebforms, kbservercontrols, kbhowtomaster, kbevent, kbctrlcreate

↑ Back to the top

Article Info
Article ID : 317794
Revision : 8
Created on : 6/25/2003
Published on : 6/25/2003
Exists online : False
Views : 560