如何:确定引发事件的 Web 服务器控件

更新:2007 年 11 月

调用事件处理程序之后,可以确定引发事件的控件。

确定哪个控件引发了事件

  1. 在事件处理程序中,声明类型与引发事件的控件匹配的变量。

  2. 将事件处理程序的 sender 参数分配给变量,将它强制转换为适当的类型。

    下面的示例演示由几个不同按钮调用的 Button 控件 click 事件的处理程序。该处理程序显示了与单击按钮有关的信息。

    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;
        }
    }
    

请参见

概念

ASP.NET Web 服务器控件事件模型

其他资源

ASP.NET 网页中的服务器事件处理

处理和引发事件