miércoles, 7 de octubre de 2009

eventhandler en C#

When you want to execute code when a certain event takes place, you can use an eventhandler. This will be "attached" to the control that will cause the event to happen (for instance, a click on a button). In the eventhandler you must call a method, which will be executed when the event occurs. If you drag a button on your form in Visual Studio 2005, and you double-click the button, the eventhandler will be generated for you, and you just need to add code. Maybe you want several things to happen when a certain button is clicked. So, you want several methods to be executed when a button is clicked. Here is how you add your own eventhandler:

Add a new eventhandler to an event (e.g.: a button click):

button1.Click += new EventHandler(test);

The method that will be called is "test". Now, of course, you need to implement "test":

void test(Object sender, EventArgs e)
{
MessageBox.Show("The test was succesful");
}

Notice the paramters. These have to be added to the method, else you will get an error when compiling ("No overload for 'test' matches delegate 'System.EventHandler'"). The sender is the object who generated the event (in this case, the button) and EventArgs is other information (e.g.: an EventArg with an datagridview can be the row- or column-index).

No hay comentarios:

Publicar un comentario