Working with Events and Event Procedures
The concept of events and event procedures has been derived from classical VB Lang., but there an event procedure can be bound with only single event of a single control, where as in .NET it can be bound with multiple events of a control as well as with multiple controls also.
Binding event procedures with multiple events of a control
Add a new form to the project Form4 and double click on it which defines an event procedure Form4_Load, now bind the same event procedure with click event of form also, to do this go to events of form, select click event and click on the drop down beside, which displays the list of event procedures available, select 'Form4_Load' event procedure that is defined previously which binds the event procedure with click event also now under the event procedure write the following code and execute:
MessageBox.Show("Event procedure bound with multiple events of a control.");
Binding an event procedure with multiple controls
Add a new form in the project i.e. Form5 and design it as below. Now double click on button1 which generates a click event procedure for button1, bind that event procedure with button2, textBox1, textBox2 and Form5 also and write the following code under the event procedure:
MessageBox.Show("Control is clicked");
Binding an event procedure with multiple controls and identifying ‘Type’ of control which is raising the event
Add a new form in the project i.e. Form6 and design it same as Form5. Now double click on button1 which generates a click event procedure for button1, bind that event procedure with button2, textBox1, textBox2 and Form6 also and write the following code under the event procedure:
if (sender.GetType().Name == "Button") MessageBox.Show("Button is clicked."); else if (sender.GetType().Name == "TextBox") MessageBox.Show("TextBox is clicked."); else MessageBox.Show("Form6 is clicked.");
When an event procedure is bound with multiple controls, any of the control can raise the event in runtime and execute the event procedure, but the object of control which is raising the event will be coming into the event procedure and captured under the parameter "sender" of event procedure as following:
As sender is of type object it's capable of storing object or instance of any class in it, so after the object or instance of the control class is captured under sender by calling GetType() method on it we can identify the type of control to which that object or instance belongs as we have performed above.