Project Type: ASP.NET Web Application
Code Behind: Visual Basic

The use of user control within a web application can be a convenient way to modularize your code. For example, suppose you want the header or footer to be the same for each page on your web site. By using a user control, you can change the control at any time without having to revisit each page.

You are allowed to have controls within control. If you have more than one child control within a control or on a page, you can access the properties of one child from within another one.

One reason you might want to do this is that you have a control that you want to appear to be more than one page. You do this by making one visible and the other invisible depending on the actions of the user.

In this example, we create a user control that has three child controls. From each of the three you can make each of the other two visible and the current control invisible.

To create each of the user controls add a new item to your project and choose type user control. Design it as you would a web page.

We will need four controls. The main control plus three child controls called Top, Middle and Bottom. You will also need a web page in order to run the control.

To place a control on a page or to place a control another control just drag it from solution explorer. When you do this VS.NET will give the control a name. If you wish to change the name, right-click on the control to view properties and change the value of "Id".

In order to expose the properties of the child control, you must add a line like this:

Protected WithEvents uctTop As Top

Substitute uctTop with the "Id" you gave the child control on the parent control. Substitute Top for the class name of the child control itself. You will see it in the first line of the control code:

Public MustInherit Class Top

Here is the code you need to access the properties of one child control from another.

Dim mParent as Control

Dim AnyControl As Middle ' Middle is the class name of the other child control

mParentControl = Me.Parent ' this identifies the Parent

AnyControl = mParentControl.FindControl("uctmiddle") ' uctMiddle is the ' id of the other child in the Parent

AnyControl.Visible = True ' make the control visible

Me.Visible = False ' makes this child control invisible


To download the complete project, visit our web site at http://www.metaprosystems.com/NetTipsTricks.htm.