21

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...

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Liran Friedman
  • 4,027
  • 13
  • 53
  • 96
  • 3
    possible duplicate of [How to pass an event to a method?](http://stackoverflow.com/questions/2560258/how-to-pass-an-event-to-a-method) – pritaeas Jan 12 '15 at 10:52

3 Answers3

27

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!

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
  • 3
    @LiranFriedman: No need to. [`EventHandler`](http://msdn.microsoft.com/en-us/library/system.eventhandler%28v=vs.110%29.aspx) is a delegate already. See its signature. – Patrick Hofman Jan 12 '15 at 11:03
1

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);
}
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

Something like this?

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

void OnSomeEvent(object sender, EventArgs e)
{

}

Passing it as an argument:

DoWork(OnSomeEvent);
Emile Pels
  • 3,837
  • 1
  • 15
  • 23