Binding an event procedure with multiple controls

Add a new form in the project i.e. Form7 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 Form7 also and write the following code under the event procedure:


if (sender.GetType().Name == "Button") {
	Button b = sender as Button;
	if (b.Name == "button1")
	   	     MessageBox.Show("Button1 is clicked"); else
	   	     MessageBox.Show("Button2 is clicked");
} else if (sender.GetType().Name == "TextBox") {
	TextBox tb = (TextBox)sender;
	if (tb.Name == "textBox1")
	   	     MessageBox.Show("TextBox1 is clicked"); else
	   	     MessageBox.Show("TextBox2 is clicked");
} else
  	  MessageBox.Show("Form7 is clicked"); 


When an event procedure is bound with multiple controls and if we want to identify the exact control which is raising the event, we need to identify the "Name" of control. But even if "sender" represents the control which is raising the event, using sender we cannot find the control name because as we are already aware that object of a class can be stored in its parent's variable and make it as a reference but with that reference we cannot access the child classes members (Rule No. 3 of Inheritance). So if we want to find the name of control that is raising the event we need to convert sender back into appropriate control type (Button or TextBox) from which it is created by performing an explicit conversion and then find out the name of control object, we can convert sender into control type in any of the following ways:


Button b = sender as Button; or Button b = (Button)sender;

TextBox tb = sender as TextBox; or TextBox tb = (TextBox)sender;