简体   繁体   中英

C# Updating TextBox From Another Class

All I am trying to do is update a textBox (in this case txtInit) from another class. I have been reading a lot about how a UI Thread has to change itself, and something about using a dispatcher. I found an answer on here that seemed close, but I couldnt get it to work for me... it said to try using the line:

MainForm.Dispatcher.Invoke(new Action(delegate() {MainForm.myInstance.txtInit.Text = "Text"};);

In my ServerSide class, I need to send a String to the txtInit textbox on my MainForm.. and that is all I need to do.. thanks for any help.

Classes have nothing to do with threads(which is your problem right now). Each Control has an Invoke method which will do the right thread synchronization for you. So you can do

MainForm.myInstance.txtInit.Invoke((sender, args) => (sender as TextBox).Text = "text");

To improve performance you can test(which basically tells you if you're in the same thread) the Control.IsInvokeRequired property.

Another way to do it is by using the SynchronizationContext of the UI thread which you need to capture in the constructor of the form from SynchronizationContext.Current and then do

syncContext.Send((obj) =>  MainForm.myInstance.txtInit.Text = "Text", null);

I would probably just create a public method on the MainForm that you can pass a string to and let that method set the text for the text box. You can also control whether or not you need to us the Invoke call (different threads) so you never have to worry about coding this in other areas - just call the method and pass the string.

Here is an example:

 public partial class Form1 : Form
    {
        public delegate void UpdateText(string text);
        public Form1()
        {
            InitializeComponent();
        }
        public void SetTextBoxText(string text)
        {
            // Check to see if invoke required - (from another thread)
            if(textBox1.InvokeRequired)
            {
                textBox1.Invoke(new UpdateText(this.SetTextBoxText),

                    new object[]{text});
            }
            else
            {
                textBox1.Text = text;
            }
        }
    }

If I understand correctly, it seems you want to access the Windows form elements from another thread or from some asynchronous events. In such case following links may help you.

  1. http://msdn.microsoft.com/en-us/library/ms171728.aspx

  2. Update UI from multiple worker threads (.NET)

  3. Controlling form elements from a different thread in Windows Mobile

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM