Wednesday, October 19, 2011

Web User Controls - Creating and using on webpages

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.

Creating User Controls

There are three 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.
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 1.



Figure 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 2 shows a simple user control created by placing two Button server controls on an HTML Grid Layout Panel control.



Figure 2. A simple user control

The control shown in Figure 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 id="pnlGrid" runat="server" style="width: 20px; position: relative; height: 48px
ms_positioning="GridLayout">

<asp:Button ID="butUp" Text="^" runat="server" />
<asp:Button ID="butDown" Text="v" runat="server" />

</div>
</form>

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 3 when you create a user control.



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

The code in Figure 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.
  4. For example, the following code shows a Value property that returns the value of the Spin control created in the preceding section:

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:

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 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:
// Declare the event.

public event EventHandler Click;

  1. 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.
  2. // Method to raise event.

    protected virtual void OnClick(EventArgs e)
    {
    if (Click != null)
    {
    Click(this, e);
    }
    }

  1. 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:
  2. 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:

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();
}

Adding the Control to a Web Form
There are two steps to consume user control in a Web application:

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

2. 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.

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="Spin.ascx" %>

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UserControlDemo.Default" %>
<HTML>
<body>
<form id="Form1" method="post" runat="server">
<uc1:Spin id="Spin1" 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="Spin.ascx" %>

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UserControlDemo.Default" %>

<HTML>
<body>
<form id="Form1" method="post" runat="server">
<h2>Creating and Using User Controls</h2>
<hr>
<asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
<uc1:Spin id="Spin1" 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 4.



Figure 4. The Spin user control on a Web form

As you’ll notice in Figure 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.

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:

protected Spin Spin1;

  1. 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:
  2. 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.

1 comment :

  1. Hi,Creating a good Web Design Cochin is an everyday task for a web designer but for the rest of the web community this task is a head-ache and a huge problem,Thanks......

    ReplyDelete