1

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.

1 Answer 1

2

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.
};
Sign up to request clarification or add additional context in comments.

3 Comments

Shouldn't OnCustomerSelected be protected virtual? (just a best practice)
I usually leave them private until otherwise necessary.
True if you develop just for yourself/your team, and you always have the code a live developing environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.