Skip navigation

Back to Basics - 30 Oct 2009

Creating and Using User Controls

This month we are going back to some of the ASP.NET basics by taking a look at creating and using user controls. A key tool that ASP.NET offers Web developers is the ability to encapsulate portions of a Web page s user interface and behavior into a simple reusable package called a user control. Prior to ASP.NET, developers generally achieved this through the use of include files. Today, however, user controls make it much easier to create and manage common elements of your Web site s user interface.

 

What Are User Controls?

User controls represent the simplest form of ASP.NET control encapsulation. Because they are the simplest, they are also the easiest to create and use. Essentially, a user control is the grouping of existing server controls into a single-container control. This enables you to create powerful objects that you can easily use throughout an entire Web project. The container used by a user control is a project file that uses an ASCX file extension and contains an @Control directive.

 

Creating User Controls

Adding a user control to your Web application project is simple, and the Visual Studio IDE gives you several ways to add the file. All of these methods will open the Add New Item dialog:

  • Select Project | Add Web User Control, as shown below:

 

  • Select File | New | File
  • Right click on the project. Select Add | Add Web User Control from the context menu.

As stated above, all of these options will open the Add New Item dialog box (as shown below). From this dialog box, select the Web User Control option and provide the name for the user control. Notice that the file extension for a user control is ASCX.

 

Once the user control is added to your project, open the file and switch to HTML view. Notice that, unlike the standard template for an ASPX Web page, which contains the basic HTML elements needed for the Web page, the user control template is basically empty, containing no HTML at all. Because the user control will be hosted in a parent Web page, it doesn t need to provide the basic HTML elements; instead, these will be provided by the parent page.

Also notice that, as shown in the listing below, rather than the @Page directive that an ASPX Web page normally contains, the user control contains the @Control page directive. This tells ASP.NET that it should treat this file as a user control rather than a Web page:

<%@ Control Language="c#" AutoEventWireup="false" Codebehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>

To demonstrate how to use a user control in your application, add a Label control to the user control you created. If you add the label in design view, you ll see that the design surface for a user control works almost identically to the design surface of a normal ASPX Web page. Change the text of the label to Sally sold seashells by the seashore as shown below.

Once you have added the label to the user control, you can simply drag the control onto an ASPX page from the Solution Explorer.

 

When you drop the control onto the Web form, it will appear as a grey box, as shown below.

Now that you have seen how easy it is to add a user control to a Web page, change the page to HTML view to see what has changed.

First, notice at the top of the page that Visual Studio has added a new @Register directive (shown below):

<%@ Register TagPrefix="uc1" TagName="WebUserControl1" Src="WebUserControl1.ascx"%> 

The @Register directive tells Visual Studio what prefix the user control uses, the tag name for the user control, and where the ASCX file for the user control is located.

Next, notice that the user control tag has been added to the Web page HTML, as shown below:

 

Running the Web form in a browser merges the parent page and the user control together into a single Web page, which is shown below.

You can see how easy it is to add a user control to your Web application and then add the user control to a Web page in the project. Next, let s look at how you can interact between the user control and its host Web form.

 

Page/Control Communication

User controls are not completely isolated from their parent Web pages. It is relatively easy for you to access controls hosted in the user control from the parent Web form, or access controls hosted on the parent Web form from the user control. Additionally, a user control can both expose properties that the parent Web form can access, as well as access public properties exposed by the host Web form.

 

Accessing User Control Controls

To access a control in the user control from the parent page, you first need to add a reference to the user control in your code-behind. When you add a user control to the design surface, unlike the in-box controls, Visual Studio does not automatically add the control declaration code to the code-behind. This means that you cannot access the control from code in the Web page s code-behind. The declaration of the Web user control you created in the previous section is shown below:

protected WebUserControl1 WebUserControl11;

Once you add the reference to the user control, you can access control via code in the code-behind and you get the full level of IntelliSense that you get with in-box controls.

There are many scenarios where you want your Web page to be able to interact with controls inside of the user control. Accessing controls in the user control is quite easy using FindControl, which exists on any container control (which a user control is). Using the FindControl method to locate the Label control in the user control created earlier is shown below:

private void Page_Load(object sender, System.EventArgs e)

{

 //Find the label in the user control

  ((Label)this.WebUserControl11.FindControl("Label1")).Text=

     "Hickory, dickory, dock, the mouse ran up the clock";

}

This sample uses code in the Web form to locate the Label control hosted in the user control and alters its text property. Remember that the FindControl method returns a generic Control object, so you need to cast the object to the appropriate control type in order to access that control type s specific properties (such as the Label s Text property).

 

Accessing Web Form Controls

You can also access server controls hosted by the parent Web form from the user control using basically the same process. The next sample uses the FindControl method from within the user control s Page_Load event to locate a Label control on the parent Web form:

private void Page_Load(object sender, System.EventArgs e)

{

 //Find the label in the parent web form

  ((Label)this.Parent.Parent.FindControl("Label1")).Text=

     "Twinkle, twinkle, little star, how I wonder what you are.";

}

Since we know that the Label resides under the root Web form, you need to use the Control class Parent property to climb up the Web form s control tree to locate the root Web form (in this case, it requires two steps up the control tree). Once the root Web form is located, the FindControl method locates the Label and modifies its text.

One problem with the above sample is the way it attempts to locate the root Web form. The code assumes that the root Web form will always be two steps up the control tree, but if this user control is being used in multiple locations throughout a Web application, it would be much better to make this process more flexible since that user control might not always be located in the same location on all pages. A much better solution to locating the root Web form is to use a recursive method, as shown below:

private System.Web.UI.Page root;

private void RecurseParents(System.Web.UI.Control c)

{

 if (c is System.Web.UI.Page)

 {

     root = ((System.Web.UI.Page)c);

     return;

 }

 RecurseParents(c.Parent);

}

The recursive RecurseParents method allows us to climb the control tree as far as needed in order to find the root Web form. The method recourses itself, each time looking to see if the container is of type System.Web.UI.Page (the ASP.NET Web page base class). Once the root form is found, it is stored in a local variable so that it can be accessed from anywhere in the class. If the control is not the root form, the recursion continues.

Using this technique, the code in the Page_Load event would be modified to execute the RecurseParents method first, as shown below:

private void Page_Load(object sender, System.EventArgs e)

{

 RecurseParents(this.Parent);

 Label l = root.FindControl("Label1");

 l.Text=

     " Twinkle, twinkle, little star, how I wonder what you are.";

}

Notice that you still use the FindControl method to locate the Label.

 

Exposing User Control Properties

Instead of accessing controls directly, sometimes it is more useful to expose properties from a user control. User controls can expose properties that can be accessed by the host Web form, as well as accessing properties exposed by the host Web form.

To create user control properties that can be accessed by their host, simply add a public property to the user control s code-behind, as shown below:

private string _usercontroltext="";

public string UserControlText

{

 get

 {

     return _usercontroltext;

 }

 set

 {

     _usercontroltext = value;

 }

}

Once you have added this public property, there are several ways you can access it from the host page. First, you can simply set the property by adding it as an attribute to the user control s HTML, as shown below:




Adding the attribute automatically populates the UserControlText property at run time with the attribute value. This technique obviously has some limitations if you need to assign a complex data type to the property.

The second way to access a user control property is to get or set the property value in the parent Web form s code-behind page, as shown below:

private void Page_Load(object sender, System.EventArgs e)

{

 this.WebUserControl11.UserControlText=

     "An apple a day sends the doctor away";

}

Once you populate the user control property, you still need to add some code to display the value of the UserControlText property in the label:

  
private void Page_Load(object sender, System.EventArgs e)

{

 this.Label1.Text = this.UserControlText;

}


Exposing Web Form Properties

You can access properties exposed by the Web form using the same basic technique you used to access the label hosted by the Web form. First, add a public property to the code-behind of the Web form, as shown below:

private string _webformtext;

public string WebFormText

{

 get

 {

     return _webformtext;

 }

 set

 {

     _webformtext = value;

 }

}

 Next, modify the RecurseParents method shown earlier so you can properly locate the root Web form:

private WebForm1 root;

private void RecurseParents(System.Web.UI.Control c)

{

 if (c is WebForm1)

 {

     root = ((WebForm1)c);

     return;

 }

 RecuseParents(c.Parent);

}

The recursive method has been modified to search for WebForm1 rather than the System.Web.UI.Page class. This is because we need to cast the root form to the specific class WebForm1 in order to be able to access the custom properties it contains.

Finally, add some code to the user control s Page_Load event that accesses the property:

private void Page_Load(object sender, System.EventArgs e)

{

 root.WebFormText =

   "Row, row, row your boat gently down the stream.";

}

Conclusion

This article has demonstrated how easy it is to create a user control in your project and how easy it can be to interact with the user control from the Web form. In future articles we ll continue to explore user controls and demonstrate some more interesting ways of utilizing these powerful ASP.NET tools to help you get the most out of your applications.

With that, we remind you to e-mail your questions to us at [email protected].

Andrew Flick is Product Manager of NetAdvantage Windows Forms Technologies & TestAdvantage for Infragistics, Inc., a Microsoft Visual Studio Industry Partner. He is responsible for spearheading product management and strategies of Infragistics Windows Forms product line. He works directly with the Director of Development to set the direction, plan, and manage product development. Andrew is a Microsoft .NET MVP and is the chair of the INETA Academic Student Committee. Contact Andrew at mailto:[email protected].

Devin Rader is an Infragistics Technology Evangelist and is responsible for authoring Infragistics reference applications and .NET technology articles, as well as the world-wide delivery of Infragistics technology demonstrations. Devin is an active member and leader for INETA, has served as the sole technical editor for numerous works, and is a contributing author for the soon to be published ASP.NET 2.0 Professional. Contact Devin at mailto:[email protected].

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish