Windows Phone Developers

Wednesday, October 22, 2008

Creating EventHandlers for WindowsForm Controls using C#

Most often we would double click the Windows form control and use the default event’s (click) handler. At times we would use other events like mousehover, change etc. The following snippet will be helpful for adding a button on a user form and adding an event handler for the same

Button btn = new Button();

btn.Text = "Sample Button";

btn.Left = 100;

btn.Top = 100;

this.Controls.Add(btn);

btn.Click += new EventHandler(btn_Click);

btn.MouseHover += new EventHandler(btn_MouseHover);

Here we are using EventHandler - a predefined delegate that specifically represents an event handler method for an event that does not generate data.

The code will link the event handler btn_Click with the click event

btn.Click += new EventHandler(btn_Click);

void btn_Click(object sender, EventArgs e)

{

MessageBox.Show("Clicked...");

}

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