Share via


How to: Connect Multiple Events to a Single Event Handler in ASP.NET Web Pages

If you already have an event handler, you can bind several control events to it. These multiple events can be from the same control or one event from several different controls, as long as the events all have the same method signature. For example, you might want to bind the Click events of several Button server controls on an ASP.NET page to a single event handler. When your handler is called, you can determine which control caused the event.

To connect multiple events to a single event handler

  • In the page markup, add the same event name and method name to each control, as in the following code example.

    <asp:Button ID="Button1" onclick="Button_Click" runat="server" 
      Text="Button1" /> 
    <br />
    <asp:Button ID="Button2" onclick="Button_Click" runat="server"
      Text="Button2" />
    

    Note

    You must make sure that the method has the correct signature for the event that it is handling.

To connect multiple events to a single event handler in Visual Basic

  • Modify the Handles clause of a method by adding the names of the events that the method should handle. Separate the event names with commas.

    The following code example shows how you can bind the Button_Click method to events raised by three Button controls.

    Sub Button_Click (ByVal sender as System.Object, _
        ByVal e as System.EventArgs) _
        Handles Button1.Click, Button2.Click, Button3.Click
    

    Note

    If you use a Handles clause to bind an event and method, do not also include the event attribute in the markup. For example, do not include an onClick attribute in the markup for a Button control. If you do, the method will be called twice.

To determine which control raised the event

  1. In the event handler, declare a variable whose type matches the controls that raise the event.

  2. Assign the first argument of the event handler to the variable, casting it to the appropriate type.

    The following code example shows the handler for a Button control's Click event that is called by several different buttons. The handler displays the ID property of the button that caused the event.

    Private Sub Button_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click, Button2.Click, Button3.Click
            Dim b As Button = CType(sender, Button)
            Label1.Text = b.ID
    End Sub
    
    private void Button_Click(object sender, System.EventArgs e)
        {
            Button b = (Button) sender;
            Label1.Text = b.ID;
        }
    

See Also

Other Resources

Server Event Handling in ASP.NET Web Pages