How to pass EventHandler as a method parameter

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

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 that this is possible, but I don’t remember how to do it ...

+4
source share
3 answers

Just use the event handler type as the 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. Remember to remove the event handler when this is done, or you may leak from memory!

+10
source

Something like that?

void DoWork(Action<object, EventArgs> handler)
{
    if (condition)
    {
        OnSomeEvent(this, EventArgs.Empty);
    }
}

void OnSomeEvent(object sender, EventArgs e)
{

}

Pass as an argument:

DoWork(OnSomeEvent);
0
source

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);
}
0

Source: https://habr.com/ru/post/1570851/


All Articles