views:

54

answers:

5

Lets say I have 2 forms. In Form1 I have a timer, which counts (count++) and in Form2 I have a text box (textBox1) which shows how much the timer has counted. Now I want to know how would I show the integer 'count' in 'textBox1' without any user interference (clicking buttons) or in other words, how would I make the data in the text box auto refresh (without using Form2 form = new Form2(); form.Show();). I want 2 separate windows, in one a running timer and in the other a textbox displaying how much the timer has counted and constantly updating (with the help of the timer, I presume).

+3  A: 

One way is by creating a public event and registering for that event from the other form.

Brian R. Bondy
A: 

You could have a singleton/static class that holds all data that are relevant to all forms, exposed as properties. All forms could write and read these properties. Additionally it fires Events that the forms can subscribe to when the properties change (in case you need live updates).

bitbonk
The singleton pattern is viewed as an anti-pattern by many these days so I would not recommend using it.
klausbyskov
You should always use what works for you.
bitbonk
+1  A: 

Simplest way: Expose a public property on Form2. In the setter for the property, set the value of the textbox. I believe the timer event fires on the UI thread, so you shouldn't have any thread safety issues. If you do, you'll have to go back to the public event approach that Brian mentioned above.

Keep in mind that you may also have to do a DoEvents() to get the UI to actually update to the user. Also keep in mind that this kind of update inherently slows down the processing of your application.

public int TimerValue 
{

    set
    {
        this.txtTextBox.Text = string.Format("{0:0000}", value);

    }
}
Robaticus
A: 

Just make your timer a public event so it can be referenced on another form.

Sir Graystar
A: 

Implement INotifyPropertyChanged on the timer form, and define a public property representing the count:

private int count;
public int Count
{
    get { return count; }
    set
    {
        if (count != value)
        {
            count = value;
            OnPropertyChanged("Count");
        }
    }
}

Then, on the textbox form, databind your textbox Text value to the Count property of the timer form.

textbox.DataBindings.Add("Text", timerForm, "Count");
Joviee