Cannot implicitly convert type 'System.EventHandler' to 'System.Windows.RoutedEventHandler' in c#

11,195

Solution 1

The signature of your event handler is wrong.

It should be:

private void btn_Click(object sender, RoutedEventArgs e)

And the Click event assignment should be changed to:

btn.Click += new RoutedEventHandler(btn_Click);//Click event

Solution 2

You need to use a RoutedEventHandler (found on the System.Windows assembly).

In your case, you should be able to change btn.Click += new EventHandler(btn_Click); with btn.Click += new System.Windows.RoutedEventHandler(btn_Click);; and then change the EventArgs ob btn_Click to RoutedEventArgs.

Make sure you add a reference to the System.Windows assembly or it won't compile!

Looking at the MSDN, I got this:

The RoutedEventHandler delegate is used for any routed event that does not report event-specific information in the event data. There are many such routed events; prominent examples include Click and Loaded.

The most noteworthy difference between writing a handler for a routed event as opposed to a general common language runtime (CLR) event is that the sender of the event (the element where the handler is attached and invoked) cannot be considered to necessarily be the source of the event. The source is reported as a property in the event data (Source). A difference between sender and Source is the result of the event being routed to different elements, during the traversal of the routed event through an element tree.

Link to the msdn.

Solution 3

Button Click is Routed Event as mentioned by Patrick Hofman.

You can even shorten if don't want new event by just writing btn.Click += btn_Click;

Share:
11,195
user88
Author by

user88

Updated on June 12, 2022

Comments

  • user88
    user88 about 2 years

    In windows phone application I want to add a button dynamically like below:

    Button btn = new Button();
    btn.Content = tb_groupname.Text;
    btn.Width = 200;
    btn.Height = 200;
    btn.Click += new EventHandler(btn_Click);//Click event
    

    But when I add click event on my button I am getting below error:

    Cannot implicitly convert type 'System.EventHandler' to 'System.Windows.RoutedEventHandler'
    

    And below is the click event method of button:

    private void btn_Click(object sender, EventArgs e)
    {
      textbox1.text = "ABC"; // For Example
    }
    

    I don't understand why its getting this error. Kindly suggest me, waiting for reply. Thanks.

  • user88
    user88 about 10 years
    it gets me another error No overload for 'btn_Click' matches delegate 'System.EventHandler'
  • Patrick Hofman
    Patrick Hofman about 10 years
    Did you change the Click assignment too?
  • Mr Moose
    Mr Moose about 10 years
    Click assignment should point to RoutedEventHandler