Creating Events in ASP.NET

Creating your own events on your own controls is something that is essential if you want you web app to work well and also provide you with reusable controls. It’s easy to skip past the problem and find another way to get your code to do what you want it to do and detect the change another way. But you end up with much nicer code if your controls can have proper events for a piece of action, and you web page can have proper event handlers on each. Not only that but the code you need to write in generally a copy and past job and not that hard.

The Code

While it’s not that hard, the amount of code that is needed is quite a lot more than you may expect. Fortunately though it’s code you going to just re-use again and again changing small bits as needed.

    //1 - Event args (use default, but eventually pass in data through here)
    public class SaveCompleteEventArgs : EventArgs
    {
        public SaveCompleteEventArgs(int inDataValue)
        {
            this.DataValue = inDataValue;
        } //end of con

        public readonly int DataValue;
    }



    //2 - define delegate
    public delegate void SaveCompleteEventHandler(object sender, SaveCompleteEventArgs e);

    //3 - define the event itself
    public event SaveCompleteEventHandler SaveComplete;

    //4 - the protected virtual method to notify registered objects of the request
    //	virtual so that it can be overridden.
    protected virtual void OnSaveComplete(SaveCompleteEventArgs e)
    {
        //if the UpdateData event is empty, then a delegate has not been added to it yet.
        if (SaveComplete != null)
        {
            //event exists, call it:
            SaveComplete(this, e);
        } //end of if
    }

    //5 - method that translates the input into the desired event
    public void TriggeringMethod(int strData)
    {

        // get new event args
        //EventArgs e = new EventArgs();
        SaveCompleteEventArgs e = new SaveCompleteEventArgs(strData);

        // call the virtual method
        OnSaveComplete(e);
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s