Taha Rehman Siddiqui
Taha Rehman Siddiqui

Reputation: 2533

Delegate: Specifying Method (or its name) in Custom Server Control, to be called

I am working on a ASP.net custom server control, with jquery, WCF and stuff. I want to give the developer, using it, the flexibility of specifying an on success function (to be called when a task is successfully done by the control) in one of the publicly exposed properties of the control. I am new with events and delegates, can someone give me an idea how should I do it? Specifying the type of the public property? Setting the function name in the property(in the markup or/and in the code, as a string or any other type)? Calling the function/delegate from the control?

Some sample code would be preferred (please spare if I said something stupid)

Upvotes: 0

Views: 96

Answers (1)

BlackBear
BlackBear

Reputation: 22979

This is the standard pattern for events:

class YourControl {
    public event EventHandler Success;

    protected void OnSuccess() {
        if(this.Success != null)
            this.Success(this, EventArgs.Empty);
    }
}

Success is of type EventHandler to integrate nicely with other events, thus allowing generic event handlers (say a general-purpose logging facility) to subscribe. The event can be easily triggered everywhere in the control and its children by calling OnSuccess().

You can also customize the event adding further information:

class YourControl {
    public class YourControlEventArgs: EventArgs {
        public TimeSpan Elapsed;
        public YourControlEventArgs(TimeSpan t) {
            this.Elapsed = t;
        }
    }

    public event EventHandler<YourControlEventArgs> Success;

    protected void OnSuccess(TimeSpan t) {
        if(this.Success != null)
            this.Success(this, new YourControlEventArgs(t));
    }
}

A specific class holds the details of the event extending the simple EventArgs to integrate with the rest of the .NET, as said above.

Upvotes: 1

Related Questions