开发者

Sending data between forms without using .Show()

Let's 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, 开发者_如何学Pythonin 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).


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


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);

    }
}


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).


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


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");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜