HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Refactoring Event Handlers - How to go about this for growing WinForms application

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
refactoringthisapplicationhandlerswinformsgrowingaboutforhowevent

Problem

I have a class with approximately 140 menu buttons in a nested ribbon-style menu over a canvas type area within a WinForms application.

As a result of this, a large swathe of my codebehind file consists of 140 event handlers for click events.

Many of them however, are remarkable similar, for example:

private void btnFinancialStatusReport(object sender, EventArgs e)
    {
        SwitchCurrentControl(new FinancialStatusReport());
    }

    private void btnMonthlySalesReport(object sender, EventArgs e)
    {
        SwitchCurrentControl(new MonthlySalesReport());
    }

    private void btnDailySalesReport(object sender, EventArgs e)
    {
        SwitchCurrentControl(new DailySalesReport());
    }


SwitchCurrentControl is a private method with the responsibility of essentially taking the newly constructed UserControl and docking it correctly into the active canvas. This is irrelevant to the question but I thought somebody might ask...

The Question

For this many buttons, (140+) a good 50% of them are practically the same, the only difference being in which Control they create.

Is this acceptable, or is there a way I can refactor this to reduce the amount of handlers?

Note

Before anybody suggests I switch to WPF btw, that is not an option...unless that same person wants to come and redo all 140 associated controls for me ;-)

Solution

You can create a Dictionary, where key is a MenuItem, a value us function/delegate that has to be called on click. All 140+ menu items subscribe to the same event hadler and in that event
handler write something like

myMenuItemsDictionary[((MenuItem)sender)]()


this is good, in case when you have no parameters to pass to a delegate, in case when you need to pass them, you can go farther:

define a class

public class MenuItemHandler
{
    delegate MethoddToInvokeOnClick()
    List parametersToPassToDelegate = ..
}


and the instances of this class have in a Value of the dictionary

Code Snippets

myMenuItemsDictionary[((MenuItem)sender)]()
public class MenuItemHandler
{
    delegate MethoddToInvokeOnClick()
    List<object> parametersToPassToDelegate = ..
}

Context

StackExchange Code Review Q#11215, answer score: 4

Revisions (0)

No revisions yet.