Simon
Simon

Reputation: 8349

How can I add an additional parameter to a button click EventHandler?

In C#, how is the best way to add an additional property to a button event call?

Here is the code for the EventHandler:

button.Click += new EventHandler(button_Click);

Here is the code for the button_Click:

private void button_Click(object sender, EventArgs e)
{

}

If I want to add a PropertyGrid parameter to the button_Click function parameters, how is the best way to do this?

I am wanting to do this as the button.Click code is in a function that has a PropertyGrid parameter, and in the button_Click function, I need to set the PropertyGrid selected object. This is only set when the button.Click button is clicked.

If I set the tag of the button to be a PropertyGrid object, how can I retrieve this tag object in the button_Click code?

The button_Click event is called from an object, and the sender is the object, that is not the button.

Can I please have some help with the code?

Upvotes: 1

Views: 5717

Answers (1)

Hans Passant
Hans Passant

Reputation: 942328

You cannot convince a Button that it should know anything about a PropertyGrid. When it fires its Click event then it can only tell you about what it knows. Which is cast in stone.

You trivially work around this by using a lambda expression, it can capture the PropertyGrid argument value and pass it on to the method. Roughly:

    private void SubscribeClick(PropertyGrid grid) {
        button.Click += new EventHandler(
            (sender, e) => button_Click(sender, e, grid)
        );
    }

Upvotes: 5

Related Questions