Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to work with delegates and event handler for user control

I have created a user control that contains a button. I am using this control on my winform which will be loaded at run time after fetching data from database.

Now I need to remove a row from a datatable on the Click event of that button.

The problem is that how do I capture that event in my form. Currently it goes in that user control's btn click event defination.

like image 460
Shantanu Gupta Avatar asked May 27 '10 10:05

Shantanu Gupta


People also ask

Can you explain me how delegate and events works?

A function that is added to delegates must be compatible with this signature. Delegates can point to either static or instance methods. Once a delegate object has been created, it may dynamically invoke the methods it points to at runtime. Delegates can call methods synchronously and asynchronously.

How are delegates used in event handling?

A delegate is a type that holds a reference to a method. A delegate is declared with a signature that shows the return type and parameters for the methods it references, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback.

How does event work with delegate in C#?

Using Delegates with EventsThe events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class. The class containing the event is used to publish the event. This is called the publisher class.

Can we use events without delegates?

Yes, you can declare an event without declaring a delegate by using Action.


1 Answers

You can create your own delegate event by doing the following within your user control:

public event UserControlClickHandler InnerButtonClick;
public delegate void UserControlClickHandler (object sender, EventArgs e);

You call the event from your handler using the following:

protected void YourButton_Click(object sender, EventArgs e)
{
   if (this.InnerButtonClick != null)
   {
      this.InnerButtonClick(sender, e);
   }
}

Then you can hook into the event using

UserControl.InnerButtonClick+= // Etc.
like image 162
djdd87 Avatar answered Oct 12 '22 22:10

djdd87