Compartilhar via


ASP.NET User Controls Overview

At times, you might need functionality in a control that is not provided by the built-in ASP.NET Web server controls. In those cases, you can create your own controls. You have two options. You can create:

  • User controls. User controls are containers into which you can put markup and Web server controls. You can then treat the user control as a unit and define properties and methods for it.

  • Custom controls. A custom control is a class that you write that derives from Control or WebControl.

User controls are substantially easier to create than custom controls, because you can reuse existing controls. They make it particularly easy to create controls with complex user interface elements.

This topic provides an overview of working with ASP.NET user controls.

User Control Structure

An ASP.NET Web user control is similar to a complete ASP.NET Web page (.aspx file), with both a user interface page and code. You create the user control in much the same way you create an ASP.NET page and then add the markup and child controls that you need. A user control can include code to manipulate its contents like a page can, including performing tasks such as data binding.

A user controls differs from an ASP.NET Web page in these ways:

  • The file name extension for the user control is .ascx.

  • Instead of an @ Page directive, the user control contains an @ Control directive that defines configuration and other properties.

  • User controls cannot run as stand-alone files. Instead, you must add them to ASP.NET pages, as you would any control.

  • The user control does not have html, body, or form elements in it. These elements must be in the hosting page.

You can use the same HTML elements (except the html, body, or form elements) and Web controls on a user control that you do on an ASP.NET Web page. For example, if you are creating a user control to use as a toolbar, you can put a series of Button Web server controls onto the control and create event handlers for the buttons.

The following example shows a user control that implements a spinner control where users can click up and down buttons to rotate through a series of choices in a text box.

Security noteSecurity Note

This example has a text box that accepts user input, which is a potential security threat. By default, ASP.NET Web pages validate that user input does not include script or HTML elements. For more information, see Script Exploits Overview.

<%@ Control Language="VB" ClassName="UserControl1" %>
<script runat="server">
    Protected colors As String() = {"Red", "Green", "Blue", "Yellow"}
    Protected currentColorIndex As Integer = 0
    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        If IsPostBack Then
            currentColorIndex = CInt(ViewState("currentColorIndex"))
        Else
            currentColorIndex = 0
            DisplayColor()
        End If
    End Sub
    
    Protected Sub DisplayColor()
        textColor.Text = colors(currentColorIndex)
        ViewState("currentColorIndex") = currentColorIndex.ToString()
    End Sub

    Protected Sub buttonUp_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        If currentColorIndex = 0 Then
            currentColorIndex = colors.Length - 1
        Else
            currentColorIndex -= 1
        End If
        DisplayColor()
    End Sub
    
    Protected Sub buttonDown_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        If currentColorIndex = colors.Length - 1 Then
            currentColorIndex = 0
        Else
            currentColorIndex += 1
        End If
        DisplayColor()
    End Sub
</script>
<asp:TextBox ID="textColor" runat="server" 
    ReadOnly="True" />
<asp:Button Font-Bold="True" ID="buttonUp" runat="server"  
    Text="^" OnClick="buttonUp_Click" />
<asp:Button Font-Bold="True" ID="buttonDown" runat="server" 
    Text="v" OnClick="buttonDown_Click" />
<% @ Control Language="C#" ClassName="UserControl1" %>
<script runat="server">
    protected int currentColorIndex;
    protected String[] colors = {"Red", "Blue", "Green", "Yellow"};
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            currentColorIndex = 
                Int16.Parse(ViewState["currentColorIndex"].ToString());
        }
        else
        {
            currentColorIndex = 0;
            DisplayColor();
        }
    }
    
    protected void DisplayColor()
    {
        textColor.Text = colors[currentColorIndex];
        ViewState["currentColorIndex"] = currentColorIndex.ToString();
    }
    
    protected void buttonUp_Click(object sender, EventArgs e)
    {
        if(currentColorIndex == 0)
        {
            currentColorIndex = colors.Length - 1;
        }
        else
        {
            currentColorIndex -= 1;
        }
        DisplayColor();
    }

    protected void buttonDown_Click(object sender, EventArgs e)
    {
        if(currentColorIndex == (colors.Length - 1))
        {
            currentColorIndex = 0;
        }    
        else
        {
            currentColorIndex += 1;
        }
        DisplayColor();
    }
</script>
<asp:TextBox ID="textColor" runat="server" 
    ReadOnly="True" />
<asp:Button Font-Bold="True" ID="buttonUp" runat="server" 
    Text="^" OnClick="buttonUp_Click" />
<asp:Button Font-Bold="True" ID="buttonDown" runat="server" 
    Text="v" OnClick="buttonDown_Click" />

Notice that the user control looks much like an ASP.NET page — it contains several controls (a TextBox control and two Button controls) and code that handles the buttons' Click events and the page’s Load event. However, the control contains no markup except for the controls, and instead of an @ Page directive it contains an @ Control directive.

Adding a User Control to a Page

You add a user control to a page by registering it on the host page. When you register it, you specify the .ascx file that contains the user control, a tag prefix, and a tag name that you will use to declare the user control on the page. For details, see How to: Include a User Control in an ASP.NET Web Page.

Defining Properties and Methods for a User Control

You can define properties and methods for a user control the same way you do for a page. By defining a property for a user control, you make it possible to set its properties declaratively and in code.

Events in User Controls

When a user control contains Web server controls, you can write code in the user control to handle the events raised by the child controls. For example, if your user control contains a Button control, you can create a handler in the user control for the button's Click event.

By default, events raised by child controls in a user control are not available to the host page. However, you can define events for your user control and raise them so that the host page is notified of the event. You do this in the same way that you define events for any class. For more information, see Raising an Event.

Referencing External Resources

When a user control runs, references to external resources such as images or anchors to other pages are resolved using the URL of the user control as the base URL. For example, if the user control contains an Image control whose ImageUrl property is set to Images/Button1.gif, the URL of the image is added to the URL of the user control to resolve the complete path to the image. If the user control references a resource that is not in a subfolder of the user control itself, you must provide a path that resolves to the correct folder at run time. For more information on specifying paths for ASP.NET server controls, see ASP.NET Web Site Paths.

Caching and User Controls

User controls can support caching directives that are separate from the host page. You can therefore add user controls to pages and to cache portions of a page. For details, see Caching Portions of an ASP.NET Page.

See Also

Other Resources

ASP.NET User Controls