I am new to user controls in webforms and I need to add an event to the control so that developers using the control can add event handlers to this event. What is the best way to go about doing this?
This control is a custom uploader control. The control uploads files to a web service asynchronously and stores a list of files that uploaded successfully in a hidden field. On the next post back I would like to read from this hidden field in the request form collection, and if it's not null then I'd like to fire a successful upload event.
To clarify, I am looking for a server-side event that I can fire. I am just not familiar with creating them.
First start off by creating a class for your event arguments.
// this can house any kind of information you want to send back with the trigger
public class MyNewEventArgs : EventArgs { ... }
Next, create the event on the control's class. this is done using a delegate, and the event itself.
// event delegate handler
public delegate void MyNewEventHandler(object s, MyNewEventArgs e);
// your control class
public class MyControl : Control
{
// expose an event to attach to.
public event MyNewEventHandler MyNewEvent;
Next you need to fire the event from your code. We do this by grabbing the event, checking for subscribers, then triggering.
// grab a copy of the subscriber list (to keep it thread safe)
var myEvent = this.MyNewEvent;
// check there are subscribers, and trigger if necessary
if (myEvent != null)
myEvent(this, new MyNewEventArgs());
More information can be found on MSDN on how to create events.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With