Windows Phone Developers

Friday, June 11, 2010

Event Handler to Handle Multiple Events (C#/.NET)

Event handlers are of great use especially in WinForms programming. There might be a case where you will be having multiple Objects (Buttons for example), which requires to fire events of same type

The following snippet shows how to declare an eventhandler and assign it to multiple events


private void btn_Click(object sender, EventArgs e)
        {
            Button b1;
            b1 =  (System.Windows.Forms.Button)sender;
            MessageBox.Show("Button Clicked := " + b1.Name.ToString());
            b1.ForeColor = Color.Red;
        }

The above event handler is a generic one. It contains two arguments the sender, which contains the object that fired the event and Arguments.

Statement
b1 = (System.Windows.Forms.Button)sender;

Assigns (or casts) the object to button object. If casting is not done Cannot implicitly convert type 'object' to 'System.Windows.Forms.Button'. An explicit conversion exists (are you missing a cast?) is thrown

The snippet below assigns the sub - btn_Click with click events of both buttons

button1.Click += new EventHandler(btn_Click); 
           button2.Click += new EventHandler(btn_Click);
Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment