开发者

Cross-thread operation not valid - listbox Clear statement

开发者 https://www.devze.com 2023-03-16 19:44 出处:网络
I am getting this error because I am trying to update my listbox from a thread that it was not originally created on:

I am getting this error because I am trying to update my listbox from a thread that it was not originally created on:

Cross-thread operation not valid: Control 'tbHistory' accessed from a thread other than

Thread t = new Thread(UpdateHistory);          // Kick off a new thread
t.Start();

private void UpdateHistory()
{
//tbHistory is a listbox
tbHistory.Items.Clear();
}

Can someone please give me the code to fix this problem? I know开发者_运维技巧 I am supposed to use invoke but the examples I found on Google don't seen to help me. The examples only seem to show how to change a label text, not clear a listbox.


You need to use the UI thread. To accomplish this, use:

private void UpdateHistory()
{
   //tbHistory is a listbox
   myForm.Invoke ((Action) (() =>tbHistory.Items.Clear()));
}

EDIT: Added missing bracket as the code wouldn't compile.

0

精彩评论

暂无评论...
验证码 换一张
取 消