Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass EventHandler as a method parameter

I am trying to write a generic method that will also handle a click event, and I want to allow the user to pass his own method as the click event. Something like this:

public static void BuildPaging(
    Control pagingControl, short currentPage, short totalPages,  ???)
{
    for (int i = 0; i < totalPages; i++)
    {
        LinkButton pageLink = new LinkButton();
        ...
        pageLink.Click += ???;
        pagingControl.Controls.Add(paheLink);
    }
}

I know it is possible but I don't remember how to do it...

like image 481
Liran Friedman Avatar asked Jan 12 '15 10:01

Liran Friedman


2 Answers

you can pass action delegate to function

public static void BuildPaging(Control pagingControl, 
            short currentPage, short totalPages,  Action<type> action)

  for (int i = 0; i < totalPages; i++)
{
    LinkButton pageLink = new LinkButton();
    ...
    pageLink.Click += action;
    pagingControl.Controls.Add(paheLink);
}
like image 45
Pranay Rana Avatar answered Oct 11 '22 16:10

Pranay Rana


Just use the type of the event handler as argument type:

public static void BuildPaging(Control pagingControl
                              , short currentPage
                              , short totalPages
                              , EventHandler eh // <- this one
                              )
{
    for (int i = 0; i < totalPages; i++)
    {
        LinkButton pageLink = new LinkButton();
        ...
        pageLink.Click += eh;
        pagingControl.Controls.Add(paheLink);
    }
}

Note: Don't forget to remove the event handler when done or you might leak memory!

like image 154
Patrick Hofman Avatar answered Oct 11 '22 17:10

Patrick Hofman