在我的Windows窗体应用程序中,我有一个textbox
和backgroundworker
组件。在dowork
的{{1}}事件中,我正在尝试访问文本框的值。我怎样才能做到这一点?当我尝试访问文本框的值时,我在dowork事件处理程序代码中遇到异常:
backgroundworker
答案 0 :(得分:6)
您只能访问 GUI线程中的textbox / form controls
,您可以这样做。
if(txtFolderName.InvokeRequired)
{
txtFolderName.Invoke(new MethodInvoker(delegate { name = txtFolderName.text; }));
}
答案 1 :(得分:2)
您需要使用MethodInvoker。像:
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 :(得分:2)
试试这个
txtFolderName.Invoke((MethodInvoker)delegate
{
string strFolderName = txtFolderName.Text;
});
答案 3 :(得分:1)
您必须在主线程上调用TextBox。
tb.Invoke((MethodInvoker) delegate
{
tb.Text = "Update your text";
});
答案 4 :(得分:1)
试试这个:
void DoWork(...)
{
YourMethod();
}
void YourMethod()
{
if(yourControl.InvokeRequired)
yourControl.Invoke((Action)(() => YourMethod()));
else
{
//Access controls
}
}
希望这个帮助。
答案 5 :(得分:0)
这是我使用的另外两种方法。
//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
...
}