Use custom events to implement communication between different forms-Part C #

Source: Internet
Author: User

In C #, "Event" is a method in which the class can notify customers of objects that meet certain conditions and certain events occur. When an event is used, the object that owns the event does not have to know who needs to be notified. Once a condition is met, the event will be automatically called to correctly notify each object to be notified. By using events, the modularization of the program is improved.

To use custom events in a program, follow these steps:

1. Declare the event
To declare an event in the class, you must first declare the delegate type of the event:
Public delegate void SelectionChangedEventHandler (object sender,
SelectionChangedEventArgs e );

Note: Because the sample program needs to pass data in the event, the SelectionChangedEventArgs derived class of EventArgs is defined.
Public class SelectionChangedEventArgs: EventArgs
{
Private string m_selection;

// This attribute is used to pass event data
Public string Selection
{
Get {return m_selection ;}
}

Public SelectionChangedEventArgs (string selection)
{
M_selection = selection;
}
}

The delegate type defines a set of parameters passed to the method for processing the event. Multiple events can share the same delegate type. Therefore, this step is required only when no suitable delegate type is declared.

Next, declare the event itself:
Public event SelectionChangedEventHandler SelectionChanged;


2. Call events
If no customer associates the delegate with this event, this field is blank; otherwise, this field references the delegate that should be called when the event is called. Therefore, when calling an event, you must first check whether it is empty and then call the event.
Public class Form2: System. Windows. Forms. Form
{
......

Public event SelectionChangedEventHandler SelectionChanged;

......

Private void combobox#selectedindexchanged (object sender, System. EventArgs e)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.