Microsoft KB Archive/317794

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

Article ID: 317794

Article Last Modified on 6/25/2003

-

APPLIES TO


 * Microsoft ASP.NET 1.0
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft ASP.NET 1.1
 * Microsoft Visual C# .NET 2003 Standard Edition

-



This article was previously published under Q317794



For a Microsoft Visual Basic version of this article, see 317515.

IN THIS TASK

 * SUMMARY
 * Create the Project and Static Control
 * Create the Dynamic Control and Hook It Up
 * Save, Build, and Run the Sample
 * REFERENCES



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
 Start Microsoft Visual Studio .NET. On the File menu, point to New, and then click Project. Click Visual C# Projects under Project Type, and then click ASP.NET Web Application under Templates. Name the project DynamicCreate .  Open the WebForm1.aspx file, and switch to HTML view. Replace the existing code between the  and  tags with the following code:  WebForm1   <meta content=&quot;JavaScript&quot; name=&quot;vs_defaultClientScript&quot;> <meta content=&quot;http://schemas.microsoft.com/intellisense/ie5&quot; name=&quot;vs_targetSchema&quot;> </HEAD> <body MS_POSITIONING=&quot;GridLayout&quot;> <form id=&quot;Form1&quot; method=&quot;post&quot; runat=&quot;server&quot;> <asp:Button id=&quot;Button1&quot; style=&quot;Z-INDEX: 100; LEFT: 23px; POSITION: absolute; TOP: 108px&quot; runat=&quot;server&quot; Text=&quot;Submit&quot; Height=&quot;27px&quot; Width=&quot;100px&quot;></asp:Button> <asp:Label id=&quot;Label4&quot; style=&quot;Z-INDEX: 105; LEFT: 23px; POSITION: absolute; TOP: 197px&quot; runat=&quot;server&quot; Width=&quot;368px&quot; EnableViewState=&quot;False&quot;></asp:Label> <asp:Label id=&quot;Label3&quot; style=&quot;Z-INDEX: 104; LEFT: 23px; POSITION: absolute; TOP: 163px&quot; runat=&quot;server&quot; Width=&quot;368px&quot; EnableViewState=&quot;False&quot;></asp:Label> <asp:Label id=&quot;Label2&quot; style=&quot;Z-INDEX: 102; LEFT: 23px; POSITION: absolute; TOP: 60px&quot; runat=&quot;server&quot; Width=&quot;86px&quot; Height=&quot;19px&quot;> TextBox2:</asp:Label> <asp:Label id=&quot;Label1&quot; style=&quot;Z-INDEX: 101; LEFT: 23px; POSITION: absolute; TOP: 28px&quot; runat=&quot;server&quot; Width=&quot;86&quot; Height=&quot;19&quot;> TextBox1:</asp:Label> </li> Return Design view to see the statically-created controls that the project will use.</li></ol>

Back to the top

Create the Dynamic Control and Hook It Up
<ol> 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.</li>  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. </li>  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 &quot;Web Form Designer generated code&quot; 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 &quot;using System.Web.UI.WebControls;&quot; TextBox1 = new TextBox; TextBox1.ID = &quot;TextBox1&quot;; TextBox1.Style[&quot;Position&quot;] = &quot;Absolute&quot;; TextBox1.Style[&quot;Top&quot;] = &quot;25px&quot;; TextBox1.Style[&quot;Left&quot;] = &quot;100px&quot;; Form1.Controls.Add(TextBox1);

TextBox2 = new TextBox; TextBox2.ID = &quot;TextBox2&quot;; TextBox2.Style[&quot;Position&quot;] = &quot;Absolute&quot;; TextBox2.Style[&quot;Top&quot;] = &quot;60px&quot;; TextBox2.Style[&quot;Left&quot;] = &quot;100px&quot;; 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 = &quot;TextBox1&quot;; //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. </li>  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 = &quot;TextBox1&quot;; TextBox2.Text = &quot;TextBox2&quot;; } } 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. </li>  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 &quot;TextBox1&quot;: Label3.Text = &quot;TextBox1 text was changed&quot;; break; case &quot;TextBox2&quot;: Label4.Text = &quot;TextBox2 text was changed&quot;; 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. </li></ol>

Back to the top

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: kbhowtomaster kbwebforms kbctrlcreate kbservercontrols kbevent KB317794

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.