How do I trigger another control's method in C#?
I want to have a background thread running a timer and if the timer function finishes in the thread I'd like it to trigger the stop button which can be used also terminate the thread prematurely.
Printable View
How do I trigger another control's method in C#?
I want to have a background thread running a timer and if the timer function finishes in the thread I'd like it to trigger the stop button which can be used also terminate the thread prematurely.
Something like this, or did I miss something?
Code:protected void Timer1_Timeout(object s, Args e)
{
StopBackgroundThread();
}
protected void Button1_Click(object s, Args e)
{
StopBackgroundThread();
}
private void StopBackgroundThread()
{
Button1.Enabled = false;
Timer1.Stop();
//etc...
}
Missed completely.
Something like:
Code:protected void Timer1_Timeout(object s, Args e)
{
If (for some reason this timer's Stop is triggered by code)
trigger Button1_Click event/method
}
protected void Button1_Click(object s, Args e)
{
StopBackgroundThread();
}
private void StopBackgroundThread()
{
Button1.Enabled = false;
Timer1.Stop();
//etc...
}
If you wish to change the Button1.Enabled property from a background thread you'll need to invoke it first otherwise it will throw an illegal cross thread exception.
An easy way is to have a seperate method for setting the Button1.Enabled property. Example:
You can use the SetButtonEnableStatus method to set the Button1.Enabled property from within the button's owner thread, or a background thread.Code:private delegate void SetButtonEnableStatusDelegate(bool enabled);
private void SetButtonEnableStatus(bool enabled)
{
if (Button1.InvokeRequired)
Button1.BeginInvoke(new SetButtonEnableStatusDelegate(SetButtonEnableStatus), enabled);
else
Button1.Enabled = enabled;
}
Code:SetButtonEnableStatus(true); // button enabled
SetButtonEnableStatus(false); // button disabled
Thanks Theoobe (for answering my next question before I posed it) :) .
For the rest of you others out there I was looking for something like:
Code:protected void Timer1_Timeout(object s, Args e)
{
If (for some reason this timer's Stop is triggered by code)
Button1_Click(null, null); //<====trigger Button1_Click event/method
}
protected void Button1_Click(object s, Args e)
{
StopBackgroundThread();
}
private void StopBackgroundThread()
{
Button1.Enabled = false;
Timer1.Stop();
//etc...
}