Liran Friedman
Liran Friedman

Reputation: 4287

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

Upvotes: 22

Views: 28055

Answers (3)

Pranay Rana
Pranay Rana

Reputation: 176946

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

Upvotes: 1

Emile P.
Emile P.

Reputation: 3962

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

Upvotes: 0

Patrick Hofman
Patrick Hofman

Reputation: 157098

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!

Upvotes: 30

Related Questions