Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set User Control's default event

I have a User Control containing a bunch of controls. I want to set the default Event of this User Control to the Click event of one of my buttons.

I know for setting default event to one of the UserControl's events I should add the attribute:

[DefaultEvent("Click")]
public partial class ucPersonSearch : UserControl
...

I'm wondering if it's possible to do something like:

[DefaultEvent("btn1_Click")]
public partial class ucPersonSearch : UserControl
...

I want to fire some methods in the form hosting this User Control at the time btn1 is clikced.

This is really a knit in my project, and you're answer will be valueable.

like image 279
Mahdi Tahsildari Avatar asked Oct 18 '25 18:10

Mahdi Tahsildari


1 Answers

You can't expose events of your class members to the outside of the class. How can others subscribe to the Click event of a Button inside your UserControl? Did you try it? It's not possible unless you make the button accessible from the outside, which is not good (everybody can change all the properties).

You have to define a new event, and fire your new event when your desired event (clicking on the button) happens:

[DefaultEvent("MyClick")]
public partial class UCPersonSearch : UserControl
{
    Button btnSearch;
    public event EventHandler MyClick;

    public UCPersonSearch()
    {
        btnSearch = new Button();
        //...

        btnSearch.Click += new EventHandler(btnSearch_Click);
    }

    void btnSearch_Click(object sender, EventArgs e)
    {
        OnMyClick();
    }

    protected virtual void OnMyClick()
    {
        var h = MyClick;
        if (h != null)
            h(this, EventArgs.Empty);
    }
}
like image 196
Mohammad Dehghan Avatar answered Oct 20 '25 07:10

Mohammad Dehghan