开发者

I have a problem with an eventhandler (c#)

This code is from one class

 Button pagebtn = new Button();
 pagebtn.T开发者_运维知识库ext = "2";

 pagebtn.Click += 
        listTopicPerPage_Click(this, new btnEventArgs() { btnNumber = 2 });

I get an underline on the eventHandler method saying..

cannot immplicitly convert type 'void' to 'System.EventHandler'.

Why is that?

Code from a different class that i created:

class btnEventArgs : EventArgs
{
    public int btnNumber { get; set; }
}


To specify the event parameters you should create a event field in your class, and rise it up on demand:

public partial class WebForm1 : System.Web.UI.Page
{
    public event EventHandler<btnEventArgs> SampleEvent;

    public void DemoEvent(int val)
    {
        // Copy to a temporary variable to be thread-safe.
        EventHandler<btnEventArgs> temp = SampleEvent;
        if (temp != null)
            temp(this, new btnEventArgs { btnNumber = val });
    }


    protected void Page_Load(object sender, EventArgs e)
    {
        Button1.Click += new EventHandler(Button1_Click);
    }

    void Button1_Click(object sender, EventArgs e)
    {
        DemoEvent(2);
    }
}

class btnEventArgs : EventArgs 
{
    public int btnNumber { get; set; } 
}

MSDN article


just try this:

pagebtn.Click += new EventHandler(listTopicPerPage_Click);


it's because your method signature of the listTopicPerPage_Click is something like

protected void listTopicPerPage_Click( object sender, EventArgs e )

There are a couple of things you can do here,

You can update your method signature to use btnEventArgs instead of EventArgs

protected void listTopicPerPage_Click( object sender, btnEventArgs e )

or you can cast your new btnEventArgs to be EventArgs and then cast it back to btnEventArgs in the method body.

pagebtn.Click += 
    listTopicPerPage_Click(this, (EventArgs) new btnEventArgs() { btnNumber = 2 });

protected void listTopicPerPage_Click( object sender, EventArgs e )
{    
   btnEventArgs bea = (btnEventArgs) e;

   ...
}    


Edit

pagebtn.Click += listTopicPerPage_Click;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜