user556396
user556396

Reputation: 597

Textbox text from background worker?

I've been trying to figure out how to get my textbox's text or other property from within a background worker. Does anybody know how to do this? I cannot pass it as a param because it needs to be real-time. Thanks for the help!

Upvotes: 5

Views: 15885

Answers (4)

bliss
bliss

Reputation: 330

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.

Upvotes: 1

DeMama
DeMama

Reputation: 1202

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

Upvotes: 2

Emond
Emond

Reputation: 50672

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

Upvotes: 2

LarsTech
LarsTech

Reputation: 81620

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

Upvotes: 9

Related Questions