Lesson 1: Creating Web User Controls

Lesson 1: Creating Web User Controls

Web user controls combine one or more server or HTML controls on a Web user control page, which can, in turn, be used on a Web form as a single control. User controls make it possible to create a single visual component that uses several controls to perform a specific task.

Once created, user controls can be used on Web forms throughout a project. However, because they are not compiled into assemblies, they have the following limitations not found with other types of controls:

  • A copy of the control must exist in each Web application project in which the control is used.

  • User controls can t be loaded in the Visual Studio .NET Toolbox; instead, you must create them by dragging the control from Solution Explorer to the Web form.

  • User control code is initialized after the Web form loads, which means that user control property values are not updated until after the Web form s Load event.

In this lesson, you ll learn how to create user controls and how to use them on a Web form.

After this lesson, you will be able to

  • Create a Web application that contains and uses user controls

  • Add properties, methods, and events to a user control

  • Include the user control on a Web form by editing the Web form s HTML

  • Enable design-time settings, such as grid layout, for a user control

Estimated lesson time: 30 minutes

Creating and Using User Controls

There are five steps to creating and using a user control in a Web application:

  1. Add a Web user control page (.ascx) to your project.

  2. Draw the visual interface of the control in the designer.

  3. Write code to create the control s properties, methods, and events.

  4. Use the control on a Web form by dragging it from Solution Explorer to the Web form on which you want to include it.

  5. Use the control from a Web form s code by declaring the control at the module level and then using the control s methods, properties, and events as needed within the Web form.

The following sections describe these steps in greater detail. The last section, Enabling Grid Layout, describes special considerations you need to take into account when working with user controls.

Creating a User Control and Drawing Its Interface

You create user controls out of other server and HTML controls in the Visual Studio .NET Toolbox. You do this by drawing the controls on a user control page, which is simply another file type in a Web application project, just like a Web form or an HTML page. User controls are identified by their .ascx file extensions.

To create a user control and add it to a Web application, follow these steps:

  1. From the Project menu, choose Add Web User Control. Visual Studio .NET displays the Add New Item dialog box.

  2. Type the name of the user control in the Name box, and click OK. Visual Studio .NET creates a new, blank user control page and adds it to the project, as shown in Figure 11-1.

    figure 11-1 a new, blank user control page

    Figure 11-1. A new, blank user control page

After you ve added a user control page to your project, create the visual interface of the control by adding server or HTML controls to it. User controls support flow layout only, so if you want to position controls on the page using grid layout, add an HTML Grid Layout Panel control to the user control as a container for the controls you want to position. Figure 11-2 shows a simple user control created by placing two Button server controls on an HTML Grid Layout Panel control.

figure 11-2 a simple user control

Figure 11-2. A simple user control

The control shown in Figure 11-2 is the Web form s equivalent of a Spin control. The control allows you to increment or decrement a value by clicking the up or down arrow. This example is used in the sections that follow; the HTML for the user control is shown here for reference:

<DIV  runat="server" style="WIDTH: 20px; POSITION: relative; HEIGHT: 48px" ms_positioning="GridLayout"> <asp:Button  Text="^" runat="server" /> <asp:Button  Text="v" runat="server" /> </DIV>

Writing the Control s Properties, Methods, and Events

You manipulate the controls you add to the user control from the user control s code module. That allows you to hide the inner workings of the control and expose the tasks the control performs as properties, methods, and events.

To edit the user control s code module, simply double-click the user control. Visual Studio .NET automatically generates the code template shown in Figure 11-3 when you create a user control.

figure 11-3 the user control code template (visual basic .net)

Figure 11-3. The user control code template (Visual Basic .NET)

The code in Figure 11-3 is similar to the generated code for a Web form, with these notable differences:

  • The user control s class is based on the System.Web.UI.UserControl base class.

    This base class provides the base set of properties and methods you use to create the control and get the control s design-time settings from its HTML attributes on the Web form.

  • The user control s Load event occurs when the control is loaded by the Web form that contains it.

    The control s Load event procedure runs after the Web form s Load event procedure, which is important to remember when you work with user controls on a Web form.

To create properties and methods for the user control that you can use from a Web form, follow these steps:

  1. Create the public property or method that you want to make available on the containing Web form.

  2. Write code to respond to events that occur for the controls contained within the user control. These event procedures do the bulk of the work for the user control.

  3. If the property or method needs to retain a setting between page displays, write code to save and restore settings from the control s ViewState.

For example, the following code shows a Value property that returns the value of the Spin control created in the preceding section:

Visual Basic .NET

Public Property Value() As Integer Get ' Return the Value. Return ViewState("Value") End Get Set(ByVal Value As Integer) ' Set the Value. ViewState("Value") = Value End Set End Property

Visual C#

public int Value { get { // Return the Value. return Convert.ToInt32(ViewState["Value"]); } set { // Set the Value. ViewState["Value"] = value; } }

The user changes the value of the Spin control by clicking the up and down buttons, so the following code increments or decrements the value, depending on which button the user clicks:

Visual Basic .NET

Private Sub butDown_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butDown.Click ' Decrement the Value. Me.Value -= 1 End Sub Private Sub butUp_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butUp.Click ' Increment the Value. Me.Value += 1 End Sub

Visual C#

private void butDown_Click(object sender, System.EventArgs e) { // Decrement the Value. this.Value -= 1; } private void butUp_Click(object sender, System.EventArgs e) { // Increment the Value. this.Value += 1; }

Adding the Control to a Web Form

User controls can be dragged directly from Solution Explorer onto a Web form. When you add a user control to a Web form in this way, Visual Studio .NET generates a @Register directive and HTML tags to create the control on the Web form.

For example, the following sample shows the HTML generated when you drag the Spin user control onto a Web form:

<%@ Register TagPrefix="uc1" TagName="Spin" src="/books/3/467/1/html/2/Spin.ascx" %> <%@ Page Language="vb" AutoEventWireup="false" Codebehind="UserControl.aspx.vb" Inherits="MCSDWebAppsVB.UserControl" %> <HTML> <body> <form  method="post" runat="server"> <uc1:Spin  runat="server" Value="5"></uc1:Spin> </form> </body> </HTML>

User controls can exist alongside and interact with other controls on a Web form. For example, the following HTML shows the Spin user control next to a TextBox control:

<%@ Register TagPrefix="uc1" TagName="Spin" src="/books/3/467/1/html/2/Spin.ascx" %> <%@ Page Language="vb" AutoEventWireup="false" Codebehind="UserControl.aspx.vb" Inherits="MCSDWebAppsVB.UserControl" %> <HTML> <body> <form  method="post" runat="server"> <h2>Creating and Using User Controls</h2> <hr> <asp:TextBox  runat="server"></asp:TextBox> <uc1:Spin  runat="server" Value="5"></uc1:Spin> </form> </body> </HTML>

Notice that the user control includes an attribute for the Value property. When the Spin control loads at run time, Microsoft ASP.NET will set the control s properties based on the attributes in the HTML. The control s attributes provide a way to set the control s properties from HTML.

When you view the preceding HTML in Visual Studio .NET s Design mode, it appears as shown in Figure 11-4.

figure 11-4 the spin user control on a web form

Figure 11-4. The Spin user control on a Web form

As you ll notice in Figure 11-4, the Web Forms Designer doesn t display the user control as it will appear at run time. Instead, it shows a sort of generic control. This is a limitation of Visual Studio .NET it can t display user controls in Design mode.

Another thing you ll notice is that the Spin control supports only flow layout on the Web form. That is a limitation of the control itself. To support grid layout and absolute positioning on the Web form, you have to add code to support the style attribute. You ll see that technique later in this lesson.

Using the Control in Code

After you ve created a user control and added it to a Web form, you can use it from the Web form s code module by following these steps:

  1. Declare the user control at the module level. For example, the following line declares the Spin user control that was added to the Web form in the preceding section:

    Visual Basic .NET

    Protected WithEvents Spin1 As Spin

    Visual C#

    protected Spin Spin1;

  2. Use the control s properties, methods, and events as you would any other control. For example, the following event procedure displays the Spin control s value in a text box:

    Visual Basic .NET

    Private Sub Page_PreRender(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.PreRender ' Display the Spin control's value. TextBox1.Text = Spin1.Value End Sub

    Visual C#

    private void Page_PreRender(object sender, System.EventArgs e) { // Display the Spin control's value. TextBox1.Text = Spin1.Value.ToString(); }

One very important thing to notice here is that the preceding code uses the Web form s PreRender event, not its Load event. If you use the Load event, you ll see only the Value set in the user control s HTML Value attribute the first time you click the Spin control. (Try it!) That s because the user control s code doesn t run until after the Web form s Load event has finished. Any changes that were saved in the control s ViewState aren t loaded until the control s Load event procedure has run.

Adding Events to the User Control

In addition to properties and methods, user controls can provide events that can respond to user actions on the Web form.

To add an event to a user control, follow these steps:

  1. Declare the event within the user control s code module. For example, the following code declares a Click event for the Spin user control:

    Visual Basic .NET

    ' Declare event for Spin control. Public Event Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    Visual C#

    // Declare the event. public event EventHandler Click;

  2. Create a method to raise the event. This step makes it easier for other classes to derive from this class, because they can override this method.

    Visual Basic .NET

    ' Method to raise event. Protected Overridable Sub OnClick(ByVal e As EventArgs) RaiseEvent Click(Me, e) End Sub

    Visual C#

    // Method to raise event. protected virtual void OnClick(EventArgs e) { if (Click != null) { Click(this, e); } }

  3. Raise the event from within the user control s code. For example, the following code raises the Click event whenever a user clicks the up or down buttons in the Spin user control:

    Visual Basic .NET

    Private Sub butDown_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butDown.Click ' Decrement the Value. Me.Value -= 1 ' Call the OnClick method. OnClick(e) End Sub Private Sub butUp_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butUp.Click ' Increment the Value. Me.Value += 1 ' Call the OnClick method. OnClick(e) End Sub

    Visual C#

    private void butDown_Click(object sender, System.EventArgs e) { // Decrement the Value. this.Value -= 1; // Call the OnClick method. OnClick(e); } private void butUp_Click(object sender, System.EventArgs e) { // Increment the Value. this.Value += 1; // Call the OnClick method. }

To use the user control event from a Web form, include the user control on a Web form, as shown in the preceding two sections, and then write an event procedure that responds to the event. For example, the following code updates a text box when the user clicks the Spin control:

Visual Basic .NET

Private Sub Spin1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Spin1.Click ' Update info from the user control's event handler. TextBox1.Text = Spin1.Value End Sub

Visual C#

 private void InitializeComponent() { // Add this line to wire the event. this.Spin1.Click += new System.EventHandler(this.Spin1_Click); } private void Spin1_Click(object sender, System.EventArgs e) { // Display the Spin control's value. TextBox1.Text = Spin1.Value.ToString(); }

Enabling Grid Layout

As mentioned, user controls don t have built-in support for the absolute positioning used by a Web form s grid layout. In ASP.NET, controls support absolute positioning through the style attribute. You can simply add a style attribute to your user control s HTML on the Web form to get design-time support for absolute positioning. For example, the following HTML creates a Spin user control that you can drag to different locations on a Web form in Design mode:

<UserControl:Spin  runat="server" Value="5"  style="Z-INDEX: 101; LEFT: 248px; POSITION: absolute; TOP: 88px"> </UserControl:Spin>

You ll see the problem with this solution as soon as you run the Web application, however. At run time, ASP.NET ignores the style attribute and displays the Spin user control using flow layout.

To make the style attribute work, you have to add a Style property to the user control to set the control s position and size based on the attribute settings. If your control uses a container, such as the Grid Layout Panel used by the Spin user control, you can simply pass the user control s style attribute to the Panel control, as shown in the following code:

Visual Basic .NET

Public Property Style() As String Get ' Return the containing Panel control's style attribute. Return pnlGrid.Attributes("style") End Get Set(ByVal Value As String) ' Set the containing Panel control's style attribute. pnlGrid.Attributes("style") = Value End Set End Property

Visual C#

public string Style { get { // Return the containing Panel control's style attribute. return pnlGrid.Attributes["style"]; } set { // Set the containing Panel control's style attribute. pnlGrid.Attributes["style"] = value; } }

You can use this same programming technique sometimes called delegation to implement other standard control attributes such as Visible, Enabled, or BackColor. Simply add a property to the user control that passes the attribute value to a containing control using the Attributes property, as shown in the preceding code.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net