• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 294
  • Last Modified:

Creating an EventHandler that takes a function as a parameter - WHEN THE FUNCTION ITSELF HAS PARAMETERS


I need to implement an EventHandler in C# that takes a function as a parameter - and where the function itself has parameters.

So far, I've found lots of stuff on EventArgs and delegates, but I just haven't been able to quite put this together.

What I have is a combobox that I want to have trigger an event when it is clicked.

    System.Windows.Forms.ComboBox comboBox = new ComboBox();

    string str = "A specific value";  //How do I pass this as a parameter to comboBoxOutputs_Clicked?

    comboBox.Click += new System.EventHandler(comboBoxOutputs_Clicked);

    //Here's the function;  I want to set the comboBox's text to "A specific value"
    private void comboBoxOutputs_Clicked(object sender, System.EventArgs e)
        System.Windows.Form.ComboBox comboBox = (ComboBox)sender;

        comboBox.Text = <I want the specific value here that can be passed in as a variable>;

I've looked at a lot of stuff on EventArgs and such, but haven't been able to come up with something workable so far.

Thanks in advance,

  • 2
3 Solutions
You can't really do that because the comboBoxOutputs_Clicked method must match the delegate that the combobox is expecting, so you really can't add any parameters. There might be a better design solution to this, but if you need a solution like you're after you might have to do something like:

string str = "a value";
comboBox.Tag = str;
comboBox.Click += new EventHandler(comboBoxOutputs_Clicked);

private void comboBoxOutputs_Clicked(object sender, System.EventArgs e)
    ComboBox comboBox = (ComboBox)sender;
    comboBox.Text = (string)comboBox.Tag;
You can't do this with the default event handler, since you don;t have control over the EventArgs; that gets created by the ComboBox.  

Where are you getting the value that you want to be shown in the ComboBox?  Can it be accessed from within the event handler?
comboBoxOutputs must match the delegate that the Click event on the combobox is expecting*

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now