C # Get textbox value in dowork backgroundworker event

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

 Cross-thread operation not valid: Control 'txtFolderName' accessed from a thread other than the thread it was created on` 
+4
source share
6 answers

You can only access textbox / form controls in the GUI thread, you can do it like this.

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

You need to use MethodInvoker . How:

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

try it

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

You will need to call your TextBox in the main thread.

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

Try the following:

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

Hope this help.

+1
source

these are two more methods that 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 ... } 
0
source

All Articles