bluemagic
bluemagic

Reputation: 29

An error No overload for 'timer_Tick' matches delegate 'System.EventHandler<object>'

I am not sure what is wrong with my code can someone help fix the error? The error is in the timer.Tick() line. It's supposed to make a stopwatch.

namespace App3
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {                
            this.InitializeComponent();
        }
        private int myCount;

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += new EventHandler<object>(timer_Tick);
            timer.Interval = TimeSpan.FromSeconds(5);
            timer.Start();    
        }


        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
        }

        private void timer_Tick(object sender, EventArgs e)
        {
            myCount++;
            Label.Text = myCount.ToString();
        }
    }

Upvotes: 3

Views: 2857

Answers (4)

Andrew
Andrew

Reputation: 11

I solved the same issue with two small changes:

1) Change second argument to type object:

INSTEAD OF THIS:

private void timer_Tick(object sender, EventArgs e)

USE THIS:

private void timer_Tick(object sender, **object** e)

2) Simplify the

INSTEAD OF THIS:

timer.Tick += new EventHandler<object>(timer_Tick);

USE THIS:

timer.Tick += timer_Tick;  // as suggested by WildCrustacean above

Upvotes: 1

WildCrustacean
WildCrustacean

Reputation: 5966

Delegate types are not required when attaching events, the compiler can figure it out for you. Try this instead:

timer.Tick += timer_Tick;

As for why you get the error currently, the EventHandler delegate is declared like this:

public delegate void EventHandler<TEventArgs>(
    Object sender,
    TEventArgs e
)

This means the type you put in the brackets represents the second argument in the function.

So when you type EventHandler<object>, the compiler looks for a function like timer_Tick(Object sender, object e) which it does not find, hence the error. To use the full delegate type, it would have to be EventHandler<EventArgs>

Upvotes: 4

It&#39;sNotALie.
It&#39;sNotALie.

Reputation: 22794

Instead of new EventHandler<object>, do new EventHandler. Or alternatively just put += timer_Tick;.

Upvotes: 1

Reed Copsey
Reed Copsey

Reputation: 564531

DispatcherTimer.Tick is an EventHandler, not an EventHandler<object>.

You need to change your code to specify this correctly:

 timer.Tick += new EventHandler(timer_Tick);

Note that this can also be written in short form, which is typically safer:

timer.Tick += timer_Tick;

Upvotes: 5

Related Questions