Share via


How to: Determine which Web Server Control Raised an Event

When an event handler is called, you can determine which control caused the event.

To determine which control caused the event

  1. In the event handler, declare a variable whose type matches the control that raised the event.

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

    The following example shows the handler for a Button-control click event that is called by several different buttons. The handler displays information about which button was clicked.

    Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles Button1.Click, Button2.Click, Button3.Click
    
        Dim b As Button
        b = CType(sender, Button)
    
        Select Case b.ID
            Case "Button1"
                Label1.Text = "You clicked the first button"
            Case "Button2"
                Label1.Text = "You clicked the second button"
            Case "Button3"
                Label1.Text = "You clicked the third button"
        End Select
    End Sub
    
    private void Button_Click(object sender, System.EventArgs e)
    {
        Button b;
        b = (Button)sender;
        switch (b.ID)
        {
            case "Button1":
                Label1.Text = "You clicked the first button";
                break;
            case "Button2":
                Label1.Text = "You clicked the second button";
                break;
            case "Button3":
                Label1.Text = "You clicked the third button";
                break;
        }
    }
    

See Also

Concepts

ASP.NET Web Server Control Event Model

Other Resources

Server Event Handling in ASP.NET Web Pages

Handling and Raising Events