Burak Gazi
Burak Gazi

Reputation: 595

C# Custom event for Custom Control WinForm

I have searched for this ,and there are several answers but I couldn't figure out how to do it.

I have a custom control with textbox and listview. When a user starts typing on the textbox the listview is filled with all possible matches to the text typed.(it is a search box for users). User is typing customer names to find the customer.

What I want to do is , when the user types in a customer and the customer is selected , I need to pass the customer name from custom control's textbox to my main project.

To do this , I think, I need a custom event, when a customer is selected , it raises an event to let the main application know.

How can I do this , thanks in advance.

Upvotes: 1

Views: 1727

Answers (1)

Maarten
Maarten

Reputation: 22945

You need to do three things.

1.Define the event in your custom control (for now, no special event arguments are added).

public event EventHandler CustomerSelected { get; set; }
private void OnCustomerSelected() {
    var customerSelected = CustomerSelected;
    if (customerSelected != null) {
        customerSelected(this, EventArgs.Empty);
    }
}

2.Fire the event when necessary. You can do this in your custom control by calling the OnCustomerSelected-method when a customer is selected.

3.Handle the event in your main form. You can do this by something like this (I've used a lambda, you can also define an eventhandler method, whatever you like).

this.customerControl1.CustomerSelected += (s,e) => {
    // This runs when a customer is selected.
};

Upvotes: 2

Related Questions