How to: Consume Events in a Web Forms Application

A common scenario in ASP.NET Web Forms applications is to populate a webpage with controls, and then perform a specific action based on which control the user clicks. For example, a System.Web.UI.WebControls.Button control raises an event when the user clicks it in the webpage. By handling the event, your application can perform the appropriate application logic for that button click.

To handle a button click event on a webpage

  1. Create a ASP.NET Web Forms page (webpage) that has a Button control with the OnClick value set to the name of method that you will define in the next step.

    <asp:Button ID="Button1" runat="server" Text="Click Me" OnClick="Button1_Click" />  
  2. Define an event handler that matches the Click event delegate signature and that has the name you defined for the OnClick value.

    protected void Button1_Click(object sender, EventArgs e)  
        // perform action  
    Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click  
        ' perform action  
    End Sub  

    The Click event uses the EventHandler class for the delegate type and the EventArgs class for the event data. The ASP.NET page framework automatically generates code that creates an instance of EventHandler and adds this delegate instance to the Click event of the Button instance.

  3. In the event handler method that you defined in step 2, add code to perform any actions that are required when the event occurs.

See also