Textbox text from background worker?

淺唱寂寞╮ 提交于 2019-12-01 08:17:22

I think you need to just invoke the property (pseudo-code):

private void bgw1_DoWork(object sender, DoWorkEventArgs e)
{
  // looping through stuff
  {
    this.Invoke(new MethodInvoker(delegate { Text = textBox1.Text; }));
  }
}

Use the ReportProgress method and event of the Background worker. That will switch to the correct thread for you.

Or if needed in WPF:

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string text = null;
    myTextBox.Dispatcher.Invoke(new Action(delegate()
    {
        text = myTextBox.Text;
    }));
}
bliss

i think you should use invoke method.

here's my example.

delegate void myDelegate(string name);
//...
private void writeToTextbox(string fCounter)
{
    if (this.InvokeRequired)
    {
        myDelegate textWriter = new myDelegate(displayFNums);
        this.Invoke(textWriter, new object[] { fCounter });
    }
    else
    {
        textbox1.Text = "Processing file: " + fileCounter + "of" + 100;
    }
}
//...

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    //...
    writeToTextbox(fileCounter.ToString());
}

in dowork i manipulate some textfile and i inform the user about how many files i have processed so far.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!