events

.Net: creating events, the cheat sheet

This is a cheat sheet on how to make events in .Net. This is not a tutorial. There are already good tutorials out there about how to create events in .Net. Read one of those if you need to learn about how to write events. Read this one, which is the basis of this cheat sheet: http://www.knowdotnet.com/articles/creatingevents.html

This short document is for those people who already now how to work with events, don't get to write events too often, but need a quick glance at the syntax and steps needed to do it. That was one long sentence to say that this is a recipe.

The scenario: you are writing an object that needs to expose an event, such
as clicking on an image within a control.

I. Simple event, which uses the framework EventHandler

1. We declare an event
public event EventHandler ImageClicked;

2. Implement the On method:
protected virtual void OnImageClicked(EventArgs args)
{
if(this.ImageClicked != null){
this.ImageClicked(this, args);
}
}

Done.

II. An event with a custom event handler

1. Create a class that derives from EventArgs as you custom event arguments

public class ImageClickedEventArgs : EventArgs
{
public string ImageUrl;

public ImageClickedEventArgs(string imageUrl)
{
this.ImageUrl = imageUrl;
}
}

2. Create a delegate to act as the event handler that uses your custom event arguments class

public delegate void ImageClickedEventHandler(object sender, ImageClickedEventArgs args);

3. Create the event, using the custom event handler delegate type

public event ImageClickedEventHandler ImageClicked;

4. Implement the On method, following the instructions above.

III. To hook up the event programmatically, in another object:
public class bogus
{
....
var imageControl = new ImageControl();

imageControl += new EventHandler(event_handler_method_name);

private void event_handler_method_name(object sender, EventArgs e)
{
...;
}
}

Asp Wizard: skipping a wizard step programmatically (also known as click next button)

Short Solution:

Wizard.MoveTo(NameOfWizardStepControl);

The long story:

Syndicate content