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.
Author by
user1941944
Updated on June 04, 2022Comments
-
user1941944 almost 2 years
In my windows forms application I have a
textbox
andbackgroundworker
component. Indowork
event of thebackgroundworker
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`