Freigeben über


How to: Create an ASP.NET User Control

User control declarative syntax is very similar to syntax used to create an ASP.NET Web page. The primary differences are that the user controls use an @ Control directive in place of an @ Page directive, and that the user controls do not include the html, body, and form elements around the content.

For more information about ASP.NET Web pages and how to create them, see Introduction to ASP.NET Web Pages. For more information about working with a user control in an ASP.NET Web page, see How to: Include a User Control in an ASP.NET Web Page.

To create a user control

  1. Create a new file and give it a name with the extension .ascx.

    For example, name your user control DisplayName.ascx.

    NoteNote

    You cannot put user controls in the Web site's App_Code folder. If a user control is in the App_Code folder, a parse error occurs when the containing page runs.

  2. Create an @ Control directive at the top of the page and specify the programming language you want to use for the control (if any).

  3. Add controls that you want the user control to display.

  4. Add code for the tasks that the user control will perform, such as handling control events or reading data from a data source.

  5. Create properties in the control if you want to be able to share information between the user control and the hosting page. You create properties as you would for any class, either as public members or with get and set accessors.

Example

The following example shows a complete user control. The user control displays a read-only text box with a number in it and two arrows that users can click to increment and decrement the value in the text box. The control exposes three properties, MinValue, MaxValue, and CurrentValue, that can be used in the hosting page.

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="Spinner" %>
<script runat="server">
    Private m_minValue As Integer = 0
    Private m_maxValue As Integer = 100
    Private m_currentNumber As Integer = 0
    Public Property MinValue() As Integer
        Get
            Return m_minValue
        End Get
        Set(ByVal value As Integer)
            If value >= Me.MaxValue Then
                Throw New Exception _
                    ("MinValue must be less than MaxValue.")
            Else
                m_minValue = value
            End If
        End Set
    End Property
    
    Public Property MaxValue() As Integer
        Get
            Return m_maxValue
        End Get
        Set(ByVal value As Integer)
            If value <= Me.MinValue Then
                Throw New Exception _
                    ("MaxValue must be greater than MinValue.")
            Else
                m_maxValue = value
            End If
        End Set
    End Property
    
    Public ReadOnly Property CurrentNumber() As Integer
        Get
            Return m_currentNumber
        End Get
    End Property
   
    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        If IsPostBack Then
            m_currentNumber = CInt(ViewState("currentNumber"))
        Else
            m_currentNumber = Me.MinValue
        End If
        DisplayNumber()
    End Sub
    
    Protected Sub DisplayNumber()
        textNumber.Text = Me.CurrentNumber.ToString()
        ViewState("currentNumber") = Me.CurrentNumber.ToString()
    End Sub

    Protected Sub buttonUp_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        If m_currentNumber = Me.MaxValue Then
            m_currentNumber = Me.MinValue
        Else
            m_currentNumber += 1
        End If
        DisplayNumber()
    End Sub
    
    Protected Sub buttonDown_Click(ByVal sender As Object, _
            ByVal e As System.EventArgs)
        If m_currentNumber = Me.MinValue Then
            m_currentNumber = Me.MaxValue
        Else
            m_currentNumber -= 1
        End If
        DisplayNumber()
    End Sub
</script>
<asp:TextBox ID="textNumber" runat="server" 
    ReadOnly="True" Width="32px" Enabled="False" />
<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="Spinner" %>

<script runat="server">
private int m_minValue;
private int m_maxValue = 100;
private int m_currentNumber = 0;
public int MinValue
{
    get
    {
        return m_minValue;
    }
    set
    {
        if(value >= this.MaxValue)
        {    
            throw new Exception("MinValue must be less than MaxValue.");
        }
        else
        {
            m_minValue = value;
        }
    }
}

public int MaxValue
{
    get
    {
        return m_maxValue;
    }
    set
    {
        if(value <= this.MinValue)
        {
            throw new 
                Exception("MaxValue must be greater than MinValue.");
        }
        else
        {
            m_maxValue = value;
        }
    }
}

public int CurrentNumber
{
    get
    {
        return m_currentNumber;
    }
}

protected void Page_Load(Object sender, EventArgs e)
{
    if(IsPostBack)
    {
        m_currentNumber =
            Int16.Parse(ViewState["currentNumber"].ToString());
    }
    else
    {
        m_currentNumber = this.MinValue;
    }
    DisplayNumber();
}

protected void DisplayNumber()
{
    textNumber.Text = this.CurrentNumber.ToString();
    ViewState["currentNumber"] = this.CurrentNumber.ToString();
}

protected void buttonUp_Click(Object sender, EventArgs e)
{
    if(m_currentNumber == this.MaxValue)
    {
        m_currentNumber = this.MinValue;
    }
    else
    {
        m_currentNumber += 1;
    }
    DisplayNumber();
}

protected void buttonDown_Click(Object sender, EventArgs e)
{
    if(m_currentNumber == this.MinValue)
    {
        m_currentNumber = this.MaxValue;
    }
    else
    {
        m_currentNumber -= 1;
    }
    DisplayNumber();
}
</script>
<asp:TextBox ID="textNumber" runat="server" 
    ReadOnly="True" Width="32px" Enabled="False" />
<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" />

The example user control includes code to define three properties, MinValue, MaxValue, and CurrentValue. Properties in user controls must be public. In this example, all three properties are created with get and set accessors to enable the control to check for values outside of an acceptable range. However, you can create a property by simply declaring a public member.

The MinValue and MaxValue properties can be set declaratively in the containing page using syntax such as the following:

<uc:Spinner ID="Spinner1" runat="server" MinValue=0 MaxValue=10 />

When the user control is initialized as part of the containing page, ASP.NET parses the declared property values and sets them in the user control automatically.

As with pages, the user control is re-initialized with each postback. Property values therefore must be stored in a persistent location between postbacks. A typical location to store property values is view state. During the Load event, you must check for a postback and reload the property values from the store. For more information about view state, see ASP.NET View State.

Robust Programming

For the example, exception handling has been simplified. In the set accessors for the MinValue and MaxValue properties, if the properties are set to an unacceptable value, the user control code throws a simple exception in which the string is hard-coded. In real applications, you should create a special exception class and not use hard-coded strings to display error information.

See Also

Tasks

How to: Include a User Control in an ASP.NET Web Page

Concepts

ASP.NET User Controls Overview