Article

ASP.NET 2.0: A Getting Started Guide

Page: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Next

Web User Controls

As you build real-world projects, you'll frequently encounter pieces of the user interface that appear in multiple places--headers or footers, navigation links, and login boxes are just a few examples. Packaging their forms and behaviors into your own controls will allow you to reuse these components just as you can reuse ASP.NET's built-in controls.

Building your own web server controls involves writing advanced VB or C# code, and is not within the scope of this book, but it's good to know that it's possible. Creating customized web server controls makes sense when you need to build more complex controls that provide a high level of control and performance, or you want to create controls that can be integrated easily into many projects.

Those of us without advanced coding skills can develop our own controls by creating web user controls. These are also powerful and reusable within a given project; they can expose properties, events, and methods, just like other controls; and they're easy to implement.

A web user control is represented by a class that inherits from System.Web.UI.UserControl, and contains the basic functionality that you need to extend to create your own controls. The main drawback to using web user controls is that they're tightly integrated into the projects in which they're implemented. As such, it's more difficult to distribute them, or include them in other projects, than it is to distribute or reuse web server controls.

Web user controls are implemented very much like normal web forms--they're comprised of other controls, HTML markup, and server-side code. The file extension of a web user control is .ascx.

Creating a Web User Control

Let's get a feel for web user controls by stepping through a simple example. Let's say that in your web site, you have many forms consisting of pairs of Label and TextBox controls, like the one shown in Figure 4.10.

1556_0430_SmartBoxTest
Figure 4.10. A simple form

All the labels must have a fixed width of 100 pixels, and the text boxes must accept a maximum of 20 characters.

Rather than adding many labels and text boxes to the form, and then having to set all their properties, let's make life easier by building a web user control that includes a Label of the specified width, and a TextBox that accepts 20 characters; you'll then be able to reuse the web user control wherever it's needed in your project.

In your Learning folder, create a new file named SmartBox.ascx. Then, add the control's constituent controls--a Label control and a TextBox control--as shown below:

Example 4.16. SmartBox.ascx (excerpt)                  
                 
<p>                  
 <asp:Label ID="myLabel" runat="server" Text="" Width="100" />                  
 <asp:TextBox ID="myTextBox" runat="server" Text="" Width="200"                  
     MaxLength="20" />                  
</p>

Label Widths in Firefox
Unfortunately, setting the Width property of the Label control doesn't guarantee that the label will appear at that width in all browsers. The current version of Firefox, for example, will not display the above label in the way it appears in Internet Explorer.

To get around this, you should use a CSS style sheet and the CssClass property, which we'll take a look at later in this chapter.

In Chapter 3, VB and C# Programming Basics, we discussed properties briefly, but we didn't explain how you could create your own properties within your own classes. So far, you've worked with many properties of the built-in controls. For example, you've seen a lot of code that sets the Text property of the Label control.

As a web user control is a class, it can also have methods, properties, and so on. Our SmartBox control extends the base System.Web.UI.UserControl class by adding two properties:

  • LabelText is a write-only property that allows the forms using the control to set the control's label text.
  • Text is a read-only property that returns the text typed by the user in the text box.

Let's add a server-side script element that will give our control two properties --one called Text, for the text in the TextBox, and one called LabelText, for the text in the Label:

Example 4.17. SmartBox.ascx (excerpt)                  
                 
<script runat="server" language="VB">                  
 Public WriteOnly Property LabelText() As String                  
   Set(ByVal value As String)                  
     myLabel.Text = value                  
   End Set                  
 End Property                  
                   
 Public ReadOnly Property Text() As String                  
   Get                  
     Text = myTextBox.Text                  
   End Get                  
 End Property                  
</script>                  
                 
Example 4.18. SmartBox.ascx (excerpt)                  
                 
<script runat="server" language="C#">                  
 public string LabelText                    
 {                  
   set                  
   {                  
     myLabel.Text = value;                  
   }                  
 }                  
 public string Text                  
 {                  
   get                  
   {                  
     return myTextBox.Text;                  
   }                  
 }                  
</script>

Just like web forms, web user controls can work with code-behind files, but, in an effort to keep our examples simple, we aren't using them here. You'll meet more complex web user controls in the chapters that follow.

When you use the SmartBox control in a form, you can set its label and have the text entered by the user, like this:

mySmartBox.LabelText = "Address:"                  
userAddress = mySmartBox.Text                  
                 
mySmartBox.LabelText = "Address:";                  
userAddress = mySmartBox.Text;

Let's see how we implemented this functionality. In .NET, properties can be read-only, write-only, or read-write. In many cases, you'll want to have properties that can be both read and write, but in this case, we want to be able to set the text of the inner Label, and to read the text from the TextBox.

To define a write-only property in VB, you need to use the WriteOnly modifier. Write-only properties need only define a special block of code that starts with the keyword Set. This block of code, called an accessor, is just like a subroutine that takes as a parameter the value that needs to be set. The block of code uses this value to perform the desired action--in the case of the LabelText property, that action sets the Text property of our Label control, as shown below:

Example 4.19. SmartBox.ascx (excerpt)                  
                 
Public WriteOnly Property LabelText() As String                  
 Set(ByVal value As String)                  
   myLabel.Text = value                    
 End Set                  
End Property

Assuming that a form uses a SmartBox object called mySmartBox, we could set the Text property of the Label like this:

mySmartBox.LabelText = "Address:"

When this code is executed, the Set accessor of the LabelText property is executed with its value parameter set to Address:. The Set accessor uses this value to set the Text property of the Label.

The other accessor you can use when defining properties is Get; this allows us to read values instead of writing them. Obviously, you aren't allowed to add a Get accessor to a WriteOnly property, but one is required for a ReadOnly property, such as Text:

Example 4.20. SmartBox.ascx (excerpt)                  
                 
Public ReadOnly Property Text() As String                  
 Get                  
   Text = myTextBox.Text                    
 End Get                  
End Property

The Text property is ReadOnly, but it doesn't need to be. If you wanted to allow the forms using the control to set some default text to the TextBox, you'd need to add a Set accessor, and remove the ReadOnly modifier.

When defining a property in C#, you don't need to set any special modifiers, such as ReadOnly or WriteOnly, for read-only or write-only properties. A property that has only a get accessor will, by default, be considered read-only:

Example 4.21. SmartBox.ascx (excerpt)                  
                 
public string Text                  
{                  
 get                  
 {                  
   return myTextBox.Text;                  
 }                  
}

Likewise, a property that has only a set accessor will be considered to be write-only:

Example 4.22. SmartBox.ascx (excerpt)                  
                 
public string LabelText                    
{                  
 set                  
 {                  
   myLabel.Text = value;                  
 }                  
}

Using the Web User Control

Once the user control has been created, it can be referenced from any ASP.NET page using the Register directive, as follows:

<%@ Register TagPrefix="prefix" TagName="name"                  
   Src="source.ascx" %>

The Register directive requires three attributes:

  • TagPrefix - the prefix for the user control, which allows you to group related controls together, and avoid naming conflicts
  • TagName - the control's tag name, which will be used when the control is added to the ASP.NET page
  • Src - the path to the .ascx file that describes the user control

After registering the control, we create instances of it using the <TagPrefix:TagName> format. Let's try an example that uses the SmartBox control. Create a new file named ControlTest.aspx in your Learning folder, and give it this content:

Example 4.23. ControlTest.aspx (excerpt)                  
                 
<%@ Register TagPrefix="sp" TagName="SmartBox"                  
   Src="SmartBox.ascx" %>                  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"                  
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">                  
<html>                  
 <head>                  
   <title>Creating ASP.NET Web Server Controls</title>                  
 </head>                  
 <body>                  
   <form id="Form1" runat="server">                  
     <sp:SmartBox id="nameSb" runat="server" LabelText="Name:" />                  
     <sp:SmartBox id="addressSb" runat="server"                  
         LabelText="Address:" />                  
     <sp:SmartBox id="countrySb" runat="server"                  
         LabelText="Country:" />                  
     <sp:SmartBox id="phoneSb" runat="server"                  
         LabelText="Phone:" />                  
   </form>                  
 </body>                  
</html>

Loading this page will produce the output we saw in Figure 4.10.

Now, this is a very simple example indeed, but we can easily extend it for other purposes. You can see in the code snippet that we set the LabelText property directly in the control's tag; we could have accessed the properties from our code instead. Here's an example:

Example 4.24. ControlTest.aspx (excerpt)                  
                 
<script runat="server" language="VB">                  
 Protected Sub Page_Load()                  
   nameSb.LabelText = "Name:"                  
   addressSb.LabelText = "Address:"                  
   countrySb.LabelText = "Country:"                  
   phoneSb.LabelText = "Phone:"                  
 End Sub                  
</script>                  
                 
Example 4.25. ControlTest.aspx (excerpt)                  
                 
<script runat="server" language="C#">                  
 protected void Page_Load()                  
 {                  
   nameSb.LabelText = "Name:";                  
   addressSb.LabelText = "Address:";                  
   countrySb.LabelText = "Country:";                  
   phoneSb.LabelText = "Phone:";                  
 }                  
</script>

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links