"Event" in C # is a way to provide notifications to this class when the object satisfies certain conditions. Using an event, an object with this event does not have to know who needs to notify, once a condition will be met, the event will be called automatically, and the object that needs to be notified correctly. By using an event, the degree of modularization of the program is improved.
To use a custom event in the program, you need to do follows:
1, declaration event
To declare events within the category, you must first declare the principal type of the event:
Public Delegate Void SelectionChangeDeventHandler (Object Sender,
SelectionChangeDeventargs E);
Explanation: Since this sample program needs to pass data in an event, it defines Eventargs's derived class SelectionChangeDeventArgs.
Public Class SelectionChangeDeventArgs: Eventargs
{
PRIVATE STRING M_SELECTION;
// This property is used to pass event data
Public String Selection
{
Get {return m_seetence;
}
Public SelectionChangeDeventArgs (String Selection)
{
m_selection = selection;
}
}
The delegate type definition is passed to a set of parameters for processing the event. Multiple events can share the same delegate type, so this step is only required when any suitable commission type has not yet been declared.
Next, declare the event itself:
Public Event SelectionChangeDeventHandler SelectionChanged;
2, call event
If no client will entrust with the event, this field will be empty; otherwise the field reference should be invoked when calling the event. Therefore, when you call an event, you will usually check if it is empty, then call the event.
Public Class Form2: System.Windows.Forms.form
{
...
Public Event SelectionChangeDeventHandler SelectionChanged;
...
Private void ComboBox1_selectedIndexchanged (Object Sender, System.Eventargs E)
{
IF (SelectionChanged! = NULL)
{
SelectionChangeDeventargs E = New SelectionChangeDeventArgs (ComboBoX1.Text);
SelectionChanged (this, e);
}
}
}
3, hook with events
In order to begin receiving event calls, the customer code first creates a delegate of the event type, which should be called from the event call. Then it uses = to write the delegate to any other delegation that may be connected.
Public Class Form1: System.Windows.Forms.form
{
...
PRIVATE FORM2 M_FRM2;
...
Public Form1 ()
{
...
M_FRM2 = New Form2 ();
/ / Hook with the event
m_frm2.seectionchanged = new selectionchangedeventhandler (frM2_selectionchanged);
}
...
Private void button1_click (Object sender, system.eventargs e) {
m_frm2.showdialog ();
}
Private void frm2_selectionchanged (Object Sender, SelectionChangeDeventArgs E)
{
// Get the data passed from the event
TextBox1.text = E.SeLection;
}
}
This example is shown in the following figure: