简体   繁体   中英

Changing LinkButton Onclick event

I'm trying to create LinkButtons Dynamically and change their onclick event from the server side like this:

        for (int i = 1; i <= pagenum; i++)
    {
        LinkButton pb = new LinkButton();
        pb.Text=i.ToString();
        pb.CommandArgument=i.ToString();
        pb.ID = "PageLink" + i.ToString()+",";
        pb.Click += new EventHandler(Method1);
        pb.Visible = true;
        PagesDiv.Controls.Add(pb);
    }

 public void Method1(object sender, EventArgs e, int pagenum)
{
    PagesDiv.Visible = true;
    TableDiv.Visible = true;
    localhost.StorageService w = new localhost.StorageService();
    DataTable dt = w.GetItemsByCategory(pagenum, categoryname.ToString());
    .................................(alot of code here...)
}

But my problem is that i'm getting an error on "pb.Click += new EventHandler(Method1);" saying: "No overload for 'Method1' matches delegate 'System.EventHandler'" I can't seem to find why it is not working...

Any help would be greatly appreciated!!!

You've added an extra parameter to your event handler. So it doesn't match the Click event handler on LinkButton . Look at yours:

public void Method1(object sender, EventArgs e, int pagenum)

And look at what it expects:

public void Method1(object sender, EventArgs e)

Hence, the error. I'm not sure how you expect pagenum to be passed in this case anyway, since it's not mentioned in the handler assignment:

pb.Click += new EventHandler(Method1);

There may be some other tricks to pass an argument to a handler, but one that's always worked for me and seems pretty straightforward is to simply wrap it in a lambda function:

pb.Click += (sender, e) => Method1(sender, e, pagenum);

This creates an anonymous method which just calls your method after capturing the value of pagenum , whatever that happens to be in the calling code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM