IN THIS CHAPTER
Web User Controls enable you to reuse the same visual elements in multiple pages. You can use Web User Controls to create standard page elements, such as standard headers or footers, navigation bars, and menus. You also can use Web User Controls to compose new controls out of multiple existing controls. For example, you can use a Web User Control to create an address form that can be used on multiple pages.
In this chapter, you will learn
How to create a standard page header
How to build an address form from other controls
How to dynamically load Web User Controls
Imagine that you need to display the same header on all the Web Form Pages in your application. You want to display the very same company logo and text at the top of every page. This is a good situation in which to create a Web User Control.
We’ll create a Web User Control that acts as a standard page header.
Add a new Web User Control to your project by selecting Add Web User Control from the Project menu. Enter the name Header.ascx
for the name of the User Control and click Open.
Type the text Standard Company Header
at the top of the Web User Control. Select the text with your mouse, select Font from the Format menu, and select Bold.
Add a horizontal rule to the Web User Control by double-clicking the Horizontal Rule element located under the HTML tab in the Toolbox.
You should notice that the process of creating a Web User Control is very similar to the process of creating a standard Web Form Page. You can design a Web User Control by dragging-and-dropping elements from the Toolbox, or you can switch to HTML view and add the HTML content manually.
Now that we’ve created the User Control, we can test it in a Web Form Page.
Add a new Web Form Page to your project named Home.aspx
.
Drag and drop the Header.ascx file from the Solution Explorer window onto the Home.aspx page (see Figure 5.1).
Right-click Home.aspx in the Solution Explorer window and select Build and Browse.
When you display the Home.aspx page, the contents of the Header Web User Control should appear at the top of the page (see Figure 5.2). You can use the same Header Web User Control in multiple Web Form Pages in your application.
As you saw in the previous section, a Web User Control is very similar to a standard Web Form Page. In fact, you can add the same event handling subroutines to a Web User Control as you can add to a Web Form Page.
You can use a Web User Control to handle control events, such as the Button Click
event. You can even handle events such as Page_Load
in a Web User Control.
For example, suppose that you want to randomly display a featured product on each page contained in your project. We’ll create a simple
ContentRotator
Web User Control that randomly displays one item from a list of items.
Add a new Web User Control to your project named ContentRotator.ascx
and click Open.
Add a Label
control to the Web User Control by double-clicking the Label
control located under the Web Forms tab in the Toolbox.
Switch to the Code Editor by selecting Code from the View menu (or by double-clicking the Designer surface).
Enter the following code for the Page_Load()
method:
C#.
private void Page_Load(object sender, System.EventArgs e) { Random objRan = new Random(); switch (objRan.Next(3)) { case 0: Label1.Text = "Hats on sale!"; break; case 1: Label1.Text = "Discount on all electronics!"; break; case 2: Label1.Text = "Buy stuff cheap!"; break; } }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Select Case Int(Rnd() * 3) Case 0 Label1.Text = "Hats on sale!" Case 1 Label1.Text = "Discount on all electronics!" Case 2 Label1.Text = "Buy stuff cheap!" End Select End Sub
The ContentRotator
Web User
Control displays a random message every time it is loaded. In the control’s Page_Load
subroutine, a random message is assigned to a Label
control.
The Page_Load
method in a Web User Control executes separately from the Page_Load
method in the page that contains the control. First the containing page’s Page_Load
method executes, and then the Web User Control’s Page_Load
method executes.
To test the ContentRotator
control in a Web Form Page, do the following:
Add a new Web Form Page to your project named Products.aspx
.
Add a Grid Layout Panel control to the Web Form Page by dragging the control from the Toolbox onto the Designer surface.
Drag and drop the ContentRotator.ascx file from the Solution Explorer window onto the Grid Layout Panel on the Designer surface.
Right-click Products.aspx in the Solution Explorer window and select Build and Browse.
Every time you refresh the Products.aspx page (by selecting Refresh from the View menu), a random message is displayed (see Figure 5.3).
Notice that we did not add the ContentRotator
control directly to the Web Form Page. Instead, we first added a Grid Layout Panel control and then we added the ContentRotator
control to the Grid Layout Panel control. Because we added the Web User Control to the Grid Layout Panel, we can precisely position the Web User Control
on the page.
You can add items
from the Toolbox, such as HTML elements and server controls, to the body of a Web User Control. For example, you can build a Web User Control from TextBox
and other form controls.
For example, suppose that you need to display an address form within multiple Web Pages. You might even need to display the same address form twice within the same page to retrieve a customer’s shipping and billing address. Instead of re-creating the address form over and over again, you can encapsulate it in a Web User Control.
Perform the following steps to create a basic address Web User Control:
Add a new Web User Control to your project named Address.ascx
and click Open.
Add a Grid Layout Panel to the Web User Control.
Add an HTML Label
element with the text Street
to the Grid Layout Panel.
Add a TextBox
control to the Web User Control next to the Street label.
Add a second HTML Label
element with the text City
to the Grid Layout Panel.
Add a second TextBox
control to the Web User Control next to the City label.
Add a third HTML Label
element with the text State
to the Grid Layout Panel.
Add a second TextBox
control to the Web User Control next to the State label.
After you add the HTML and form elements to the Address
control, the Designer surface should resemble Figure 5.4.
If you want to be
able to read the contents of the Street, City, and State TextBox
controls from a Web Form Page that contains the Address
control, you need to expose the TextBox
controls through properties of the Address
control.
Switch to the Code Editor by selecting Code from the View menu.
Add three properties to the Web User Control by entering the following code:
C#.
namespace myApp { using System; using System.Data; using System.Drawing; using System.Web; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; /// <summary> /// Summary description for Address. /// </summary> public abstract class Address : System.Web.UI.UserControl { protected System.Web.UI.WebControls.TextBox TextBox1; protected System.Web.UI.WebControls.TextBox TextBox2; protected System.Web.UI.WebControls.TextBox TextBox3; public string Street { get { return TextBox1.Text; } set { TextBox1.Text = value; } } public string City { get { return TextBox2.Text; } set { TextBox2.Text = value; } } public string State { get { return TextBox3.Text; } set { TextBox3.Text = value; } } private void Page_Load(object sender, System.EventArgs e) { // Put user code to initialize the page here } } }
VB.NET.
Public MustInherit Class Address Inherits System.Web.UI.UserControl Protected WithEvents TextBox1 As System.Web.UI.WebControls.TextBox Protected WithEvents TextBox2 As System.Web.UI.WebControls.TextBox Protected WithEvents TextBox3 As System.Web.UI.WebControls.TextBox Public Property Street() As String Get Return TextBox1.Text End Get Set(ByVal Value As String) TextBox1.Text = Value End Set End Property Public Property City() As String Get Return TextBox2.Text End Get Set(ByVal Value As String) TextBox2.Text = Value End Set End Property Public Property State() As String Get Return TextBox3.Text End Get Set(ByVal Value As String) TextBox3.Text = Value End Set End Property Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Put user code to initialize the page here End Sub End Class
Now that you’ve added a Street
, City
, and State
property to the Web User Control, you can access the values of the TextBox
controls contained in the User
Control from within a Web Form Page.
Let’s go ahead and create an order form that contains areas for customers to enter both a shipping and a mailing address.
Add a new Web Form Page
to your project named OrderForm.aspx
.
Add an HTML Label
with the text Shipping Address
to the Web Form Page.
Add a Flow Layout Panel control to the Web Form Page by dragging the control from the Toolbox onto the Designer surface beneath the Shipping Address label.
Drag and drop the Address.ascx file from the Solution Explorer window onto the Flow Layout Panel.
Add a second HTML Label
with the text Billing Address
to the Web Form Page beneath the Flow Layout Panel.
Add a second Flow Layout Panel control to the Web Form Page by dragging the control from the Toolbox onto the Designer surface beneath the Billing Address label.
Drag and drop the Address.ascx file, a second time, from the Solution Explorer window onto the Flow Layout Panel.
Right-click OrderForm.aspx in the Solution Explorer window and select Build and Browse.
After you complete these steps, you should see the page in Figure 5.5. Notice that the same Address form fields appear twice—for the Billing Address and the Shipping Address.
In a real-world project, you’ll need to retrieve the values entered into the address form fields and save the data to a database. We’ll discuss database access in detail in the second part of this book, “Working with Database Data.” Here, we’ll simply retrieve all the values entered into the Shipping and Billing address form fields and display the values in a Label
control.
Before we can
access any properties of the Web User Control within our Web Form Page, we need to declare each instance of the Address
control in the page.
Open the OrderForm.aspx in the Code Editor by selecting Code from the View menu.
Enter the following two lines of code at the top of the OrderForm
class declaration:
C#.
protected Address Address1; protected Address Address2;
VB.NET.
Protected WithEvents Address1 As Address Protected WithEvents Address2 As Address
Normal Web Form controls, such as the TextBox
and Label
controls, are automatically declared in the code-behind file when you drag the controls from the Toolbox. Because a Web User Control is added from the Server Explorer window, you must add the declarations to the code-behind file manually.
Next, we’ll add
a Button
and Label
control to the
OrderForm.aspx page.
Switch back to the Designer by selecting Designer from the View menu.
Add a Label
control to the OrderForm.aspx page by dragging the control from under the Web Forms tab in the Toolbox onto the Designer surface. Place the Label
control on the right side of the page.
Add a Button
control to the OrderForm.aspx page by dragging the control from under the Web Forms tab in the Toolbox onto the Designer surface.
Double-click the Button
control. This will switch you to the Code Editor.
Enter the following code for the Button1_Click
subroutine:
C#.
private void Button1_Click(object sender, System.EventArgs e) { Label1.Text = "Shipping Address:" + "<li>" + Address1.Street + "<li>" + Address1.City + "<li>" + Address1.State + "<p>Billing Address:" + "<li>" + Address2.Street + "<li>" + Address2.City + "<li>" + Address2.State; }
VB.NET.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click With Label1 .Text = "Shipping Address:" .Text &= "<li>" & Address1.Street .Text &= "<li>" & Address1.City .Text &= "<li>" & Address1.State .Text &= "<p>Billing Address:" .Text &= "<li>" & Address2.Street .Text &= "<li>" & Address2.City .Text &= "<li>" & Address2.State End With End Sub
Right-click OrderForm.aspx in the Solution Explorer window and select Build and Browse.
If you enter values into the Address form fields and click the Button
control, the contents of the form fields will appear in the Label
control (see Figure 5.6). The contents of the Address form fields are retrieved in the Button1_Click
subroutine. Address1
represents the first instance of the Address
control, the Shipping Address, and Address2
represents the second instance, the Billing
Address.
You can programmatically add Web User Controls to a page. This is useful when you need to change the layout of a page to fit different circumstances.
For example, suppose that you want to randomly display one of a group of featured product descriptions on a Web page. Furthermore, suppose that you want each featured description to be stored in separate Web User Controls.
Create a new Web User Control named Featured1.ascx
.
Type the text Apples on Sale!
onto the Designer surface.
Create a second Web User Control named Featured2.ascx
.
Type the text Books on Sale!
onto the Designer surface.
Create a new Web Form page named ShowFeatured.aspx
.
Add a PlaceHolder
control to the page.
Double-click the Designer surface to switch to the Code Editor and enter the following code for the Page_Load()
method:
C#.
private void Page_Load(object sender, System.EventArgs e) { Control ctlFeatured = null; Random objRan = new Random(); switch (objRan.Next(2) ) { case 0: ctlFeatured = LoadControl( "Featured1.ascx" ); break; case 1: ctlFeatured = LoadControl( "Featured2.ascx" ); break; } PlaceHolder1.Controls.Add( ctlFeatured ); }
VB.NET.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ctlFeatured As Control Select Case Int(Rnd() * 2) Case 0 ctlFeatured = LoadControl("Featured1.ascx") Case 1 ctlFeatured = LoadControl("Featured2.ascx") End Select PlaceHolder1.Controls.Add(ctlFeatured) End Sub
Right-click the ShowFeatured.aspx page in the Solution Explorer window and select Build and Browse.
Each time you open the ShowFeatured.aspx page, one of the two Web User Controls is randomly loaded into the page by calling the LoadControl()
method of the Page
class. The Web User Control is inserted into the
PlaceHolder
control.
In this chapter, you learned how to build Web User Controls to create reusable user interface elements. For example, you learned how to create a standard header for all the Web Form Pages in your project by building a header Web User Control. You also learned how to create Web User Controls that display dynamic content and contain form elements. Finally, you looked at how you could dynamically load Web User Controls from the hard drive.