Tag: Delegates

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//1 - Event args (use default, but eventually pass in data through here)
2public class SaveCompleteEventArgs : EventArgs
3{
4 public SaveCompleteEventArgs(int inDataValue)
5 {
6 this.DataValue = inDataValue;
7 } //end of con
8
9 public readonly int DataValue;
10}
11
12//2 - define delegate
13public delegate void SaveCompleteEventHandler(object sender, SaveCompleteEventArgs e);
14
15//3 - define the event itself
16public event SaveCompleteEventHandler SaveComplete;
17
18//4 - the protected virtual method to notify registered objects of the request
19// virtual so that it can be overridden.
20protected virtual void OnSaveComplete(SaveCompleteEventArgs e)
21{
22 //if the UpdateData event is empty, then a delegate has not been added to it yet.
23 if (SaveComplete != null)
24 {
25 //event exists, call it:
26 SaveComplete(this, e);
27 } //end of if
28}
29
30//5 - method that translates the input into the desired event
31public void TriggeringMethod(int strData)
32{
33
34 // get new event args
35 //EventArgs e = new EventArgs();
36 SaveCompleteEventArgs e = new SaveCompleteEventArgs(strData);
37
38 // call the virtual method
39 OnSaveComplete(e);
40}