This documentation is archived and is not being maintained.

Handling User Control Events

.NET Framework 1.1

There is little difference between writing event-handling methods for a user control and writing the same for a Web Forms page. Keep in mind, however, that user controls encapsulate their own events and send the event information through the containing page to be processed. Do not include user control event handlers in the containing page; write them in the code declaration block of the user control or in the code-behind file that generates the user control. For information on how to create event handlers for ASP.NET server controls, see Server Event Handling in Web Forms Pages.

To encapsulate user control events in the control

  1. Include a code declaration block in the user control that contains event-handling code for your form.
    Note   You must include all server controls involved in the user control's events in the user control itself, or use the FindControl method to locate and access a particular control's functionality.

    The following code, included in a file with the .ascx extension, will run when the Button Web server control is clicked.

    <h3> <u>User Control</u> </h3>
    <script language="VB" runat=server>
       Sub EnterBtn_Click(Sender as Object, E as EventArgs)
          Label1.Text = "Hi " & Name.Text & " welcome to ASP.NET!"
       End Sub
    </script>
    Enter Name: <asp:textbox id="Name" runat=server/>
    <asp:button Text="Enter" OnClick="EnterBtn_Click"
    runat=server/>
    <br><br>
    <asp:label id="Label1" runat=server/>
    [C#]
    <h3> <u>User Control</u> </h3>
    <script language="C#" runat=server>
    void EnterBtn_Click(Object Sender, EventArgs E){
    Label1.Text = "Hi " + Name.Text + " welcome to ASP.NET!";
        }
    </script>
    Enter Name: <asp:textbox id="Name" runat=server/>
    <asp:button Text="Enter" OnClick="EnterBtn_Click"
    runat=server/>
    <br><br>
    <asp:label id="Label1" runat=server/>
    
  2. Declare the user control in the Web Forms pages where you want the user control to appear.
    Note   The code in this procedure interacts with the code from Including a User Control in a Web Forms Page.

See Also

Web Forms User Controls | Creating a User Control | Including a User Control in Another Web Forms Page | Server Event Handling in Web Forms Pages | Handling User Control Events

Show: