Call a method from another method - c#

I have this code:
public void StartTimer()
{
var timer = new DispatcherTimer();
timer.Tick += Something;
timer.Interval = new TimeSpan(0, 0, 0, 3);
timer.Start();
}
private async void Something()
{
//code goes here....
}
The problem is that I get this error:
No overload for 'Something' matches delegate
'System.EventHandler'
My question is probably basic: why I get this error and how can I fix it...

The property Tick is of type EventHandler.
The signature of EventHandler is:
public delegate void EventHandler(
Object sender,
EventArgs e
)
Which means your Something method must match this signature. Change it to:
public void Something(Object sender, EventArgs e) { ... }
Alternatively, if you can't change the signature of that method, you can create a new delegate that calls your method.
timer.Tick += (s, e) => Something();

The DispatcherTimer.Tick event expects a handler that takes an object and an EventArgs argument:
private void Something(object o, EventArgs e)
{
// implementation
}

The signature of Something does not match that specific event. Look into the documentation for that event to see how it's done.

Try This
public void StartTimer()
{
var timer = new DispatcherTimer();
timer.Tick += Something;
timer.Interval = new TimeSpan(0, 0, 0, 3);
timer.Start();
}
private async void Something(Object sender, EventArgs e)
{
//code goes here....
}

Related

Countdown timer using System.Timers.Timer in WPF application [duplicate]

How can I implement the following in my piece of code written in WPF C#?
I have a ElementFlow control in which I have implemented a SelectionChanged event which (by definition) fires up a specific event when the control's item selection has changed.
What I would like it to do is:
Start a timer
If the timer reaches 2 seconds then launch a MessageBox saying ("Hi there") for example
If the selection changes before the timer reaches 2 seconds then the timer should be reset and started over again.
This is to ensure that the lengthy action only launches if the selection has not changed within 2 seconds but I am not familiar with the DispatcherTimer feature of WPF as i am more in the know when it comes to the normal Timer of Windows Forms.
Thanks,
S.
Try this:
private int timerTickCount = 0;
private bool hasSelectionChanged = false;
private DispatcherTimer timer;
In your constructor or relevant method:
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1); // will 'tick' once every second
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
And then an event handler:
private void Timer_Tick(object sender, EventArgs e)
{
DispatcherTimer timer = (DispatcherTimer)sender;
if (++timerTickCount == 2)
{
if (hasSelectionChanged) timer.Stop();
else MessageBox.Show("Hi there");
}
}
Finally, to make this work, you just need to set the hasSelectionChanged variable when the selection has changed according to your SelectionChanged event.
I've figured the complete code out as such:
DispatcherTimer _timer;
public MainWindow()
{
_myTimer = new DispatcherTimer();
_myTimer.Tick += MyTimerTick;
_myTimer.Interval = new TimeSpan(0,0,0,1);
}
private void ElementFlowSelectionChanged(object sender, SelectionChangedEventArgs e)
{
_counter = 0;
_myTimer.Stop();
_myTimer.Interval = new TimeSpan(0, 0, 0, 1);
_myTimer.Start();
}
private int _counter;
public int Counter
{
get { return _counter; }
set
{
_counter = value;
OnPropertyChanged("Counter");
}
}
private void MyTimerTick(object sender, EventArgs e)
{
Counter++;
if (Counter == 2)
{
_myTimer.Stop();
MessageBox.Show(“Reached the 2 second countdown”);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler e = PropertyChanged;
if (e != null)
{
e(this, new PropertyChangedEventArgs(propertyName));
}
}
look here is the code of how to use DispatherTimer and you can add your own logic in it. that will depends on you..
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(2000);
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, object e)
{
// show your message here..
}
To use a DispatcherTimer:
private DispatcherTimer _timer;
public void StartTimer()
{
if (_timer == null)
{
_timer = new DispatcherTimer();
_timer.Tick += _timer_Tick;
}
_timer.Interval = TimeSpan.FromSeconds(2);
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Hi there");
_timer.Stop();
}
void SelectionChangedEvent()
{
StartTimer();
}

Windows Phone - Increment a value

How can I increment a value per second, when I passed it from another page?
Here is some code , where I get the value from the previous page + I added the Timer.
The Problem is that the EventHandler that has to been created for the Tick, can t be set to OnNavigatedTo.
public partial class Page1 : PhoneApplicationPage
{
DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(.1) };
public Page1()
{
InitializeComponent();
this.timer.Tick += new EventHandler(OnNavigatedTo);
this.Loaded += new RoutedEventHandler(OnNavigatedTo);
}
private void ButtonToPage1(object sender, RoutedEventArgs e)
{
App app = Application.Current as App;
MessageBox.Show(app.storeValue);
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
int test = (int.Parse(QueryStr));
}
try this:
DispatcherTimer tmr;
int test;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
test = (int.Parse(QueryStr));
LoadTimer();
}
public void LoadTimer()
{
tmr = new DispatcherTimer();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
tmr.Interval = new TimeSpan(0, 0, 1);
tmr.Tick += tmr_Tick;
tmr.Start();
});
}
void tmr_Tick(object sender, EventArgs e)
{
test++;
TextBlock.Text = test.ToString();
}
It isn't clear why you can't just follow the tutorial linked in your comment. I guess you misunderstand it and tried to handle Tick event using OnNavigatedTo() method. Yes, that won't work and you aren't supposed to do so.
You're supposed to simply attach event handler method in OnNavigatedTo :
private int myNumber;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
myNumber = (int.Parse(QueryStr));
DispatcherTimer newTimer = new DispatcherTimer();
newTimer.Interval = TimeSpan.FromSeconds(1);
//attach event handler method for Tick event
newTimer.Tick += OnTimerTick;
//or attach anonymous method so you don't need OnTimerTick() method :
//newTimer.Tick += (o, e) => { myNumber++; };
newTimer.Start();
}
void OnTimerTick(Object sender, EventArgs args)
{
myNumber++;
}

Use a other Method in a static method

How can I use the method ChangeText in my static method timer_Elapsed?
public Load()
{
InitializeComponent();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
// I can't transfer parameters here
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
//Its underlined in red. I need a object reference?
ChangeText();
}
public void ChangeText()
{
label1.Text = label1.Text + ".";
}
I don't see any reason why timer_Elapsed should be static. So simply remove it.
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
ChangeText(); //Its not underlined anymore, you have an object reference
}
Another way would be to make ChangeText static. But that won't work since you want to set a Label's Text, so you need an instance of the Form anyway.
As first, your method (timer_Elapsed) could not me static, in order to use an instance property (label1)
There is an other problem in your code: Timer create an other thread, an most of windows control properties can be modified only by UI thread. Your code will throw a CrossThreadException.
In order to resolve your problem , you should modify your code with this:
if(this.InvokeRequired) {
BeginInvoke(
new MethodInvoker(delegate { label.Text+="."; }));
} else {
label.Text+=".";
}
Regards
Make ChangeText a static method.
public static void ChangeText()
Only static methods are called from a static method,
Either make your ChangeText() method to static or make your time_Elapsed method to non-static
You cannot call instance methods in static ones without creating an instance first. You have to create an instance of the class this method belongs to. like below:
var instance = new Load();
instance.ChangeText();
Update:
As other answers suggested, you should reconsider defining timer_Elapsed as static.
Hi Can you try like below:
public Load()
{
InitializeComponent();
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 1000;
// I can't transfer parameters here
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
private delegate void ChangeLabel();
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
var ChangeLabel = new ChangeLabel(ChangeText);
this.BeginInvoke(ChangeLabel);
}
private void ChangeText()
{
label1.Text = label1.Text + ".";
}

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();
}
}
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;
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>
Instead of new EventHandler<object>, do new EventHandler. Or alternatively just put += timer_Tick;.
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

how to remove the listening of callback on anonymous method?

I wrote some class:
public class A
{
public A()
{
serviceAdapter.CompletedCallBackEvent += new EventHandler( foo );
.
.
.
}
void foo(object sender, EventArgs e)
{
serviceAdapter.CompletedCallBackEvent -= new EventHandler( foo );
}
}
Now, i want to change this callback listener with some anonymous - but i don't know how to remove the callback listener in the anonymous method .
class A
{
public A()
{
serviceAdapter.CompletedCallBackEvent += delegate( object sender, EventArgs ee )
{
... need to remove the listener to the event.
}
}
}
You could simply assign your delegate/handler to a private variable.
private EventHander _handler = null;
public A()
{
_handler = delegate( object sender, EventArgs ee)
{
ServiceAdapter.CompletedCallBackEvent -= _handler;
};
ServiceAdapter.CompletedCallBackEvent += _handler;
}
You can't remove the anonymous delegate like that. See MSDN article on anonymous delegates. Also worth reading this article
You may be able to do:
public A()
{
EventHandler myHandler = null;
myHandler = new EventHandler(delegate(object s, EventArgs e)
{
serviceAdapter.CompletedCallbackEvent -= myHandler;
});
serviceAdapter.CompletedCallBackEvent += myHandler;
}

Categories

Resources