Sean Duggan
Sean Duggan

Reputation: 1135

How to properly send different parameters down for a standard Button Click

I know this has to have an easy answer, but I'm utterly failing to fathom the wealth of information on custom events, event handlers, and delegates. I have a custom messagebox class. I am trying to add the capability to do something based off of the state of a check box if the OK button is clicked. The buttons and the checkbox are added dynamically based upon input into a static Show method somewhat like the following:

if (!String.IsNullOrWhiteSpace(suicideCheckboxID))
{
    suicideCheckBox = new CheckBox();
    suicideCheckBox.AutoSize = true;
    suicideCheckBox.Text = "Do not show this message again.";
    suicideCheckBox.Location = new Point(xMargin, label.Bottom + yMargin);
    suicideCheckBox.Checked = false;

    suicideCheckBoxHeight = suicideCheckBox.Height;

    form.Controls.Add(suicideCheckBox);
}

Button okButton = NewButton(DialogResult.OK, scaleFactor);

int x = (form.Width - okButton.Width) / 2;
okButton.Location = new Point(x, buttonYPosition);

form.Controls.Add(okButton);
form.AcceptButton = okButton;
form.CancelButton = okButton;

That's not the exact code, but it's fairly representative. My impulse is to use okButton.Clicked += new EventHandler(OKButton_clicked), but if I do that, the event generated only carries arguments for object sender and EventArgs e and I really need it to operate off of the state of the checkbox and an additional piece of text to indicate which messagebox is being shown so that the values can be stored in the registry.

My first attempt was to do something like okButton.Clicked += processSuicideCheckbox(suicideCheckboxID, suicideCheckBox);, but that seems to just process the contents and allow one to return an EventHandler that points to a method with the signature of object sender and EventArgs e. What am I missing here? What is the best way to pass in the arguments actually relevant to me?

Upvotes: 1

Views: 43

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61379

You don't get to choose what is in the event handler for the Click event. Microsoft has already done that. You are stuck with the (object sender, EventArgs e) signature.

You do have a couple options:

  1. Simply store the state in the class itself; the event handler will have access to it because it is inside the class.

  2. Utilize a closure to do the same thing:

    myButton.Click += (s, e) => ActualFunction(checkBox1.Checked);
    

Note that using the closure (via a lambda expression) is just hiding the details of maintaining this state (creating the class-level variables).

Upvotes: 1

Related Questions