Microsoft Knowledge Base Article
This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved.
Terms
of Use |
Trademarks
HOW TO: Dynamically Create Controls in ASP.NET with Visual Basic .NET
This article was previously published under Q317515
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
- In Visual Studio .NET, create a new Web project by using
Visual Basic .NET. Name the project DynamicCreate.
- 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>
- Switch back to Design view to see the statically created
controls that the project will use.
Create the Dynamic Control and Hook it Up
- In Solution Explorer, click Show All Files. The list of files that are associated with WebForm1.aspx
appears. Open WebForm1.aspx.vb.
- 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. - 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. - 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. - 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.
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
| kbctrlcreate kbevent kbhowtomaster kbservercontrols kbwebforms KB317515 |
Community Feedback System
Very often, it takes hours to solve a problem. Very often, you've looked high
and low, and have tried a lot of solutions. When you finally found it, chances
are, it was because someone else helped you. Here's your chance to give back.
Use our community feedback tool to let others know what worked for you and what
didn't.
Please also understand that the community feedback system is not warranted to be
correct, it's simply a system that we've built to let people try and help each
other. If something in a feedback response doesn't make sense to you, or you're
not comfortable making changes that the feedback talks about (like registry
edits), please consult a professional.
Thank you for using kbAlertz.com Feedback System.
-- Scott Cate
|
gdw
|
Reported as Irrelevant
|
| Written:
8/18/2004 1:31 PM |
|
|
|
Jen
|
Reported as Irrelevant
|
| Written:
8/23/2004 11:24 PM |
|
|