Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Dynamically Adding Controls : Page 2

Adding controls at runtime provides the flexibility to design user interfaces that can be different things to different users. By the end of this article you'll be using multiple Placeholder controls to build a fexible template page.


advertisement
Basic ASP.NET Page Architecture
Before you can start adding controls you need to make sure you understand a few architectural issues. ASP.NET pages are built from controls. Everything on the page is a control. Labels, TextBoxes, Command Buttons, DataGrids, static text, and even the HTMLForm are all represented by a control.

The Page.Controls collection contains a reference to every control contained on a page.

Private Sub cmdSave_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles cmdSave.Click Dim oControl As Control For Each oControl In Page.Controls Me.ControlsList(oControl) Next End Sub Private Sub ControlsList(ByVal oPassed As Object) Dim oControl As Control Response.Write("Container:"+oPassed.ID+"<P>") For Each oControl In oPassed.Controls Response.Write(oControl.ID + "<P>") Next End Sub

The above two procedures contain code that loops through the controls on a form and displays the ID property. The cmdSave_Click loops through the Controls collection on the page and passes each control to the ControlsList procedure, which loops through a container control and lists all the controls.

Adding Controls Programmatically
You add controls to a page (or other container controls as you'll see shortly) by adding controls to the Controls collection. That seems pretty straightforward to me. You call the Add() method to add a control to the Controls collection. The Add() method causes the control to be appended to the end of the Controls collection. You can add a control to a specific location in the Controls collection by using the AddAt() method.

Private Sub Page_Load(_ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load Dim i As Integer For i = 1 To 5 Controls.Add(New LiteralControl("Cool<br>")) Next End Sub

The above code adds five Literal controls that each display the word "Cool" on the page. The resulting Web page appears in Figure 1.



Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.