dviddddd dviddddd - 4 months ago 34
C# Question

c# Get variable value from Form when value changed with timer in usercontrol

I have a usercontrol which have timer

public partial class Cumle : UserControl
{
private bool cond=false;

//Some Code....

private void timer2_Tick(object sender, EventArgs e)
{
//Some Code....
if(//some condition...)
cond=true;
}
}


I am working on windows form.I want to display a message box which shows me that cond is true.I want to make this stuff without using timer on Form.

public partial class Form1 : Form
{
//What I must write here?
}

Answer

You need to add a public event to your UserControl, and subscribe to it from your main form.

Something like this should do it:

public partial class Cumle : UserControl
{
   public event Action<bool> ConditionChanged = delegate {};

   private bool cond=false;

   //Some Code....

   private void timer2_Tick(object sender, EventArgs e)
   {
       //Some Code....
       if(//some condition...)
       {
           cond=true;
           ConditionChanged(cond);
       }
   }
}

Then in your form:

public partial class Form1 : Form
{
    void SubscribeToConditionChanged()
    {
        myUserControl.ConditionChanged += ShowDlg;
    }

    void ShowDlg(bool condition)
    {
        MessageBox.Show("....");
    }
}