Beruflich Dokumente
Kultur Dokumente
Overview
Delegate
Binds events to methods
Can be bound to single or multiple methods
When an event is recorded by an application
The control raises the event by invoking the delegate
for the event
The delegate in turn calls the bound method
public
public delegate
delegate void
void AlarmEventHandler(object
AlarmEventHandler(object
sender,
sender, AlarmEventArgs
AlarmEventArgs e);
e);
Event delegates are multicast, which means that they can hold references to
more than one event handling method. Delegates allow for flexibility and fine-
grain control in event handling. A delegate acts as an event dispatcher for the
class that raises the event by maintaining a list of registered event handlers for
the event. For more information on Delegates, see Delegate Class in the
Visual Studio .NET help.
Module 2: Working With Controls 5
}}
*****************************ILLEGAL FOR NON-TRAINER USE******************************
Introduction Functionality is added to controls by raising and consuming events. Before your
application can respond to an event, you must create an event handler. The
event handler (event procedure) contains the program logic that runs when the
event is raised.
Definition An event handler is a method (generally a sub procedure) that is bound to an
event. When the event is raised, the code within the event handler runs. You can
use the same event handler to handle more than one event. For example, you
can create a single event handler to handle events of a button and a menu item
that are used for the same purpose. Similarly, if you have a group of
RadioButton controls on a form, you could create a single event handler and
have each control's Click event bound to the single event handler.
Example of event The following code example is an event handler for the Click event of a button.
handler
private void button1_Click(object sender, System.EventArgs e)
{
The following code example shows how you can use a single event handler to
handle events for multiple controls.
6 Module 2: Working With Controls
Event handler Each event handler provides two parameters that allow you to handle the event
parameters properly.
The first parameter (Sender in the previous code example), provides a
reference to the object that raised the event. It specifies the source that
raised the event.
The second parameter (e in the previous code example), passes an object
specific to the event being handled. This parameter contains all of the data
that is required to handle the event.
Module 2: Working With Controls 7
private
private void
void button1_Click(object
button1_Click(object sender,
sender,
System.EventArgs
System.EventArgs e)
e)
{{
MessageBox.Show("MyHandler
MessageBox.Show("MyHandler received
received the
the event");
event");
}}
}
8 Module 2: Working With Controls
this.button2.Click
this.button2.Click +=
+= new
new
System.EventHandler(this.button1_Click);
System.EventHandler(this.button1_Click);