如何:使用 Web Form 應用程式中的事件How to: Consume Events in a Web Forms Application

ASP.NET Web Form 應用程式中的常見使用情況是使用控制項填入網頁,然後根據使用者所按的控制項,執行特定動作。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. 例如,當使用者在網頁中按一下 System.Web.UI.WebControls.Button 控制項時,控制項就會引發事件。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.

若要處理網頁上按鈕的 Click 事件To handle a button click event on a webpage

  1. 建立具有 Button 控制項的 ASP.NET Web Form 網頁 (網頁),其中 OnClick 值設定為您將在下一個步驟中定義的方法名稱。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. 定義比對 Click 事件委派簽章且採用您為 OnClick 值所定義名稱的事件處理常式。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  
    

    Click 事件針對 EventHandler 使用委派類型,並針對事件資料使用 EventArgs 類別。The Click event uses the EventHandler class for the delegate type and the EventArgs class for the event data. ASP.NET 網頁架構會自動產生程式碼,該程式碼會建立EventHandler 執行個體,並將這個委派執行個體加入至 Click 介面的 Button 事件。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. 在步驟 2 中定義的事件處理常式方法中加入程式碼,在事件發生時執行所需的任何動作。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