Поделиться через


Consuming Events

To consume an event in an application, you must provide an event handler (an event-handling method) that executes program logic in response to the event and register the event handler with the event source. This process is referred to as event wiring. For an overview of the event model in the .NET Framework, see Events and Delegates. The visual designers for Windows Forms and for Web Forms provide rapid application development (RAD) tools that simplify or hide the details of event wiring.

This topic walks you through a simple example that illustrates the details of event wiring. Suppose you want to create a user interface that has a button and a text box, and you want the background color of the text box to change when the user clicks the button. The following examples show how to program such an event-based user interface in Web Forms and in Windows Forms. For background about the Web Forms programming model, see Programming Web Forms. For background about Windows Forms, see Introduction to Windows Forms.

Consuming an Event in a Web Forms Application

Suppose you have created a simple Web Forms page (ASP.NET page) that has a Button control and a TextBox control, as shown in the following example.

<asp:TextBox id = "Box" Text = "Hello" BackColor = "Cyan" runat=server/>
<asp:Button id = "Button" Text = "Click Me" runat = server/>

If you want your page to handle a button click, you must know the type of the Click event. The Click event of System.Web.UI.WebControls.Button control is declared as follows.

public event EventHandler Click;
[Visual Basic]
Public Event Click As EventHandler

The declaration shows that the type for the Click event is EventHandler, which is a delegate type. To handle the Click event, you must supply an event handler (event-handling method) that has the signature of EventHandler. The following code shows the signature of EventHandler.

public delegate void EventHandler(object sender, EventArgs e); 
[Visual Basic]
Public Delegate Sub EventHandler(ByVal sender As Object, ByVal e As EventArgs)

By convention, event delegates in the .NET Framework have two parameters, the source that raised the event and the data for the event. The event data class derives from System.EventArgs. If the event does not generate data, it uses EventArgs as the event data type.

Your event handler for the Click event must have the following signature.

void Button_Clicked((object sender, EventArgs e){}
[Visual Basic]
Sub Button_Clicked(sender As Object, e As EventArgs)

Note   An event delegate in the .NET Framework is named EventNameEventHandler, while the term event handler in the documentation refers to an event-handling method. The logic behind the naming scheme is that an EventNameEventHandler delegate points to the event handler (the method) that actually handles the event.

To wire the Button_Clicked method to the Click event of Button, add the syntax shown in bold in the following code.

<asp:Button
        id = "Button" OnClick = "Button_Clicked" Text = "Click Me" 
        runat = server/>

The following Web Forms page handles the Click event of Button to change the background color of TextBox. The elements in bold in this example show the event handler code and how the event handler is wired to the Click event of Button.

<html>
   <script language="C#" runat=server> 
private void Button_Clicked(object sender, EventArgs e){         Box.BackColor = System.Drawing.Color.LightGreen;      }
   </script>
   <body> 
      <form method="POST" action="Events.aspx" runat=server>   
          Click the button, and notice the color of the text box.<br><br>
         <asp:TextBox 
         id = "Box" Text = "Hello" BackColor = "Cyan" runat=server/>             
         <br><br>       
        <asp:Button
        id = "Button" OnClick = "Button_Clicked" Text = "Click Me" 
        runat = server/>         
      </form>
   </body>
</html>
[Visual Basic]
<html>
   <script language="VB" runat=server> 
      Private Sub Button_Clicked(sender As Object, e As EventArgs)
         Box.BackColor = System.Drawing.Color.LightGreen
      End Sub
   </script>
   <body> 
      <form method="POST" action="Events.aspx" runat=server>   
          Click the button, and notice the color of the text box.<br><br>
         <asp:TextBox 
         id = "Box" Text = "Hello" BackColor = "Cyan" runat=server/>             
         <br><br>       
        <asp:Button
        id = "Button" OnClick = "Button_Clicked" Text = "Click Me" 
        runat = server/>         
      </form>
   </body>
</html>

To see how event handling works in Web Forms, save the page above to a file with an .aspx extension (which indicates that the file is an ASP.NET page) and deploy it anywhere in your IIS virtual root directory.

The following list summarizes the essential steps in the sample.

  • The source of the event is an instance of the System.Web.UI.WebControls.Button server control.

  • The button raises a Click event.

  • The delegate for the Click event is EventHandler.

  • The page has an event handler called Button_Clicked.

  • Button_Clicked is wired to the Click event using the following page syntax: OnClick = "Button_Clicked".

    Note A Web Forms application developer can wire the event declaratively as shown in the last bullet item without directly working with the delegate. The ASP.NET page framework generates code that creates an instance of EventHandler that references

    Button_Clicked

    and adds this delegate instance to the Click event of the Button instance.

Consuming an Event in a Windows Forms Application

Suppose you have created a simple form that contains a button and a text box control, as shown in the following code fragment.

private TextBox box;
private Button button;
[Visual Basic]
Private box As TextBox
Private myButton As Button

System.Windows.Forms.Button has a Click event whose event delegate is EventHandler. To handle the Click event, your event handler must have the signature of EventHandler. The following example shows an event handler, Button_Clicked, that has the same signature as EventHandler.

void Button_Clicked(object sender, EventArgs e){}
[Visual Basic]
Sub Button_Clicked(sender As Object, e As EventArgs)

Note   An event delegate in the .NET Framework is named EventNameEventHandler, while the term event handler in the documentation refers to an event-handling method. The logic behind the naming scheme is that an EventNameEventHandler delegate points to the event handler (the method) that actually handles the event.

To wire your event handler to the Button, you must create an instance of EventHandler that takes a reference to Button_Clicked in its argument and add this delegate instance to the Click event, as shown in the following example.

button.Click += new EventHandler(this.Button_Clicked);
[Visual Basic]
AddHandler button.Click, AddressOf Me.Button_Clicked

Note   A designer such as Visual Studio .NET will do this event wiring for you by generating code that is similar to that in the example.

The following sample shows a simple Windows Forms application that handles the Click event of Button to change the background color of TextBox. The elements in bold show the event handler and how it is wired to the Click event of the Button.

using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Drawing;
public class MyForm : Form 
{  
   private TextBox box;
   private Button button;
   
   public MyForm() : base() 
   {  
      box = new TextBox();
      box.BackColor = System.Drawing.Color.Cyan;
      box.Size = new Size(100,100);
      box.Location = new Point(50,50);
      box.Text = "Hello";
      
      button = new Button();
      button.Location = new Point(50,100);
      button.Text = "Click Me";
      
      // To wire the event, create
      // a delegate instance and add it to the Click event.
      button.Click += new EventHandler(this.Button_Clicked);
      Controls.Add(box);
      Controls.Add(button);   
   }
   // The event handler.
   private void Button_Clicked(object sender, EventArgs e)    {      box.BackColor = System.Drawing.Color.Green;   }
   // STAThreadAttribute indicates that Windows Forms uses the
   // single-threaded apartment model.
   [STAThreadAttribute]
   public static void Main(string[] args) 
   {
      Application.Run(new MyForm());
   }  
}
[Visual Basic]
Option Explicit
Option Strict

Imports System
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.Drawing

Public Class MyForm
   Inherits Form
   Private box As TextBox
   Private WithEvents button As Button
   
   Public Sub New()
      box = New TextBox()
      box.BackColor = System.Drawing.Color.Cyan
      box.Size = New Size(100, 100)
      box.Location = New Point(50, 50)
      box.Text = "Hello"
      
      button = New Button()
      button.Location = New Point(50, 100)
      button.Text = "Click Me"
      
      Controls.Add(box)
      Controls.Add(button)
   End Sub
   
   ' The event handler.
   Private Sub Button_Clicked(sender As Object, e As EventArgs) Handles button.Click
      box.BackColor = System.Drawing.Color.Green
   End Sub
   
   ' STAThreadAttribute indicates that Windows Forms uses the
   ' single-threaded apartment model.
   <STAThreadAttribute()> _
   Public Shared Sub Main(args() As String)
      Application.Run(New MyForm())
   End Sub
End Class

To see how event handling works in Windows Forms, save the preceding code to a file (with a .cs extension for a C# file and .vb for Visual Basic .NET), compile, and execute. For example, if the source file is named WinEvents.cs (or WinEvents.vb), execute the following command.

csc /r:System.DLL /r:System.Windows.Forms.DLL /r:System.Drawing.DLL WinEvents.cs
[Visual Basic]
csc /r:System.DLL /r:System.Windows.Forms.DLL /r:System.Drawing.DLL WinEvents.vb

Your executable file will be named WinEvents.exe.

The following list summarizes the essential steps in the sample.

  • The source of the event is an instance of the System.Windows.Forms.Button control.
  • The button raises a Click event.
  • The delegate for the Click event is EventHandler.
  • The form has an event handler called Button_Clicked.
  • Button_Clicked is wired to the Click event.

The code in this sample was written without using a visual designer such as Visual Studio .NET and contains only essential programming elements. If you use a designer, it will generate additional code.

The Event Pattern

While the details of event wiring differ in Windows Forms and Web Forms because of the different levels of support provided by different RAD tools, both scenarios follow the same event pattern, which has the following characteristics.

  • A class that raises an event named EventName has the following member.

    public event EventNameEventHandler EventName;
    [Visual Basic]
    Public Event EventName As EventNameEventHandler
    
  • The event delegate for the EventName event is EventNameEventHandler, with the following signature.

    public delegate void EventNameEventHandler(object sender, EventNameEventArgs e);
    [Visual Basic]
    Public Delegate Sub EventNameEventHandler(sender As Object, e As EventNameEventArgs)
    

To consume the EventName event, your event handler must have the same signature as the event delegate.

void EventHandler (object sender, EventNameEventArgs e) {}
[Visual Basic]
Sub EventHandler(sender As Object, e As EventNameEventArgs)

The Click event in the examples does not have any associated data. It uses the EventArgs class for event data and EventHandler as the delegate. Events that do have associated data use classes that derive from EventArgs from the event data type, and the corresponding event delegate type. For example, if you want to handle a MouseUp event in a Windows Forms application, the event data class is MouseEventArgs and the event delegate is MouseEventHandler. Note that several mouse events use a common class for event data and a common event delegate, so the naming scheme does not exactly match the convention described above. Your event handler must have the following signature.

void Mouse_Moved(object sender, MouseEventArgs e){}
[Visual Basic]
Sub Mouse_Moved(sender As Object, e As MouseEventArgs)

In the simple examples in this topic, the logic provided by the event handlers does not depend on the sender or on the event data. In general, the event handler provides logic that uses information provided by event source object and by the event data object. For an example, see Event Sample.

Note   Events also arise outside the context of user interfaces (UIs), and, in fact, the .NET Framework includes many non-UI classes that raise events. However, all events have the pattern described here.

Raising an Event

See Also

Events and Delegates | Raising an Event