Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 829
user88 Avatar asked May 27 '14 07:05

user88


2 Answers

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
like image 138
Patrick Hofman Avatar answered Sep 20 '22 02:09

Patrick Hofman


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.

like image 24
Nahuel Ianni Avatar answered Sep 21 '22 02:09

Nahuel Ianni