如何:在 Web 窗体应用程序中使用事件How to: Consume events in a Web Forms app

ASP.NET Web 窗体应用程序中的一种常见情况是使用控件填充网页,然后根据用户单击的控件执行特定操作。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.

处理网页上的按钮单击事件Handle a button-click event on a webpage

  1. 创建一个具有 Button 控件的 ASP.NET Web 窗体页,并将控件的 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