Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom event for a user control in webforms?

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.

Edit

To clarify, I am looking for a server-side event that I can fire. I am just not familiar with creating them.

like image 502
Chev Avatar asked Dec 22 '22 12:12

Chev


1 Answers

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.

like image 174
Brad Christie Avatar answered Dec 24 '22 01:12

Brad Christie