HOW TO:判斷引發事件的 Web 伺服器控制項
更新:2007 年 11 月
當呼叫事件處理常式時,您可判斷哪一個控制項造成事件。
若要判斷哪一個控制項造成事件
在事件處理常式中,宣告型別符合引發事件的控制項的變數。
指派事件處理常式的 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; } }