Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reuse event handler good practice in C#

Tags:

c#

.net

In my current project, I am using four grid views in different tabs. As the system has developed, they have some shared methods, such as show a custom tooltip and a right click menu for when on rows.

I am now going through a code cleaning exercise. What I see below is that I now have four event handlers calling the same method. Is it OK to change the event handlers all to point directly to GridMenu, avoiding the extra code? Will this cause me problems later in development?

Obviously at present I am using the default even handler names.

private void grdEnquiriesLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
    {
        GridMenu(sender, e);
    }

    private void grdApplicantsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
    {
        GridMenu(sender, e);
    }

    private void grdApplicationsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
    {
        GridMenu(sender, e);
    }

    private void grdInterviewsLevel1_ShowGridMenu(object sender, GridMenuEventArgs e)
    {
        GridMenu(sender, e);
    }

    private void GridMenu(object sender, GridMenuEventArgs e)
    {
        GridView view = (GridView)sender;

        if (view.CalcHitInfo(e.Point).InRow)
            popupMenu1.ShowPopup(Cursor.Position);
    }
like image 515
PeteT Avatar asked Dec 30 '22 03:12

PeteT


1 Answers

Instead of registering directly to GridMenu, create a general event handler named Grid_ShowGridMenu.

Just register to the same event handler for each grid, instead of creating a separate event handler per grid.

grdEnquiriesLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdApplicantsLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdApplicationsLevel1.ShowGridMenu += Grid_ShowGridMenu;
grdInterviewsLevel1.ShowGridMenu += Grid_ShowGridMenu;


private void Grid_ShowGridMenu(object sender, GridMenuEventArgs e)
{
    GridMenu((GridView)sender, e.Point); 
}

Now, instead of passing sender, e directly to GridMenu, pass only necessary values to GridMenu and change the signature of GridMenu so it can be more reusable.

private void GridMenu(GridView grid, Point hitPoint) 
{
    if (grid.CalcHitInfo(hitPoint).InRow)
        popupMenu1.ShowPopup(Cursor.Position);
}
like image 189
dance2die Avatar answered Jan 12 '23 03:01

dance2die