C# Get Textbox value in backgroundworker dowork event

12,618

Solution 1

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

Solution 2

try this

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

Solution 3

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

Solution 4

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

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

Solution 5

Try This:

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

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

Hope This Help.

Share:
12,618
user1941944
Author by

user1941944

Updated on June 04, 2022

Comments

  • user1941944
    user1941944 almost 2 years

    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`