Question

This can seems like a simple question ... the crux is how to match the button delegate signature void, object, eventargs with my method or use an event delegate.

As an example, I have code for a button that changes color when it's clicked. However,

button1.Click += new EventHandler(KK.ChangeColor);

carries the EventArgs from the button to the ChangeColor(object sender, EventArgs e) method, but is meaningless to the rest of the code which use ColorEventArgs; and

button1.Click += delegate(object sender, EventArgs e){ KK.ChangeColor(sender); };

doesn't allow for later removal of the delegate later in the code.

So which is better? Adding unnecessary parameters to all my methods to match the button delegate or suffering from not being able to remove the delegate later ?

or How would I change the delegate signature of the button? It seems there must be a 'cleaner' way to do this?

Will appreciate advice.

Was it helpful?

Solution

"It seems there must be a 'cleaner' way to do this?"

In my opinion, better design would depends on what exactly ChangeColor method do. If it is doing only specific operation that closely related to event button clicked, I would just leave it as the real event handler method. That means, it should have required parameters to match Button.Click event handler signature (I don't think there is option to "change the delegate signature") :

void ChangeColor(object sender, EventArgs e)
{
    MessageBox.Show("Button {0} clicked!!!", ((Button)sender).Name);
}

Otherwise, if it is doing not only specific operation related to event button clicked, I would refactor codes unrelated to button click event to another method. This way, the other method doesn't need to have unnecessary parameters. For example :

void ChangeColor(object sender, EventArgs e)
{
    var buttonName = ((Button)sender).Name;
    MessageBox.Show("Button {0} clicked!!! Save form data", );
    //assume that form name can be determined from name of button being clicked
    SaveFormToDatabase(buttonName);
}

private void SaveFormToDatabase(string formName)
{
    //save form specified in parameter
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top