user1941944
user1941944

Reputation: 329

C# Get Textbox value in backgroundworker dowork event

In my windows forms application I have a textbox and backgroundworker component. In dowork event of the backgroundworker I am trying to access value of the textbox. How can i do that? I'm getting following exception in dowork event handler code when I try to access value of the textbox:

Cross-thread operation not valid: Control 'txtFolderName' accessed from a thread other than the thread it was created on`

Upvotes: 5

Views: 13068

Answers (6)

YHTAN
YHTAN

Reputation: 686

this is the another 2 methods i use.

    //save the text value of txtFolderName into a local variable before run the backgroundworker. 
    string strFolderName;
    private void btnExe_Click(object sender, EventArgs e)
    {
        strFolderName = txtFolderName.text;
        backgroundworker.RunWorkerAsync();
    }

    private void backgroundworker_DoWork(object sender, DoWorkEventArgs e)
    {
        backgroundworkerMethod(strFolderName);//get the value from strFolderName
        ...
    }

    ----------------------------------------------------
    private void btnExe_Click(object sender, EventArgs e)
    {
        backgroundworker.RunWorkerAsync(txtFolderName.text);//pass the value into backgroundworker as parameter/argument
    }

    private void backgroundworker_DoWork(object sender, DoWorkEventArgs e)
    {
        backgroundworkerMethod(e.Argument.ToString());//get the value from event argument
        ...
    }

Upvotes: 0

Adil
Adil

Reputation: 148140

You can only access textbox / form controls in GUI thread, you can do so like that.

if(txtFolderName.InvokeRequired)
{
    txtFolderName.Invoke(new MethodInvoker(delegate { name = txtFolderName.text; }));
}

Upvotes: 7

Rajeev Kumar
Rajeev Kumar

Reputation: 4963

try this

  txtFolderName.Invoke((MethodInvoker)delegate
            {
                string strFolderName = txtFolderName.Text;
            });  

Upvotes: 3

Sharique Hussain Ansari
Sharique Hussain Ansari

Reputation: 1456

Try This:

void DoWork(...)
{
    YourMethod();
}

void YourMethod()
{
    if(yourControl.InvokeRequired)
        yourControl.Invoke((Action)(() => YourMethod()));
    else
    {
        //Access controls
    }
}

Hope This Help.

Upvotes: 1

animaonline
animaonline

Reputation: 3804

You will have to invoke your TextBox on the main thread.

tb.Invoke((MethodInvoker) delegate
{
    tb.Text = "Update your text";
});

Upvotes: 1

Habib
Habib

Reputation: 223287

You need to use MethodInvoker. Like:

BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object sender, DoWorkEventArgs e)
 {
       MethodInvoker mi = delegate { txtFolderName.Text = "New Text"; };
       if(this.InvokeRequired)
           this.Invoke(mi);
 };

Upvotes: 2

Related Questions