[英]Access ListBox.SelectedItems from another thread
我有一個名為lstProductGroups的ListBox
。
在簡單的Windows窗體上,稱為GetGroups
的方法為我提供了用戶選擇的字符串組,例如Cars, Bikes
等。
public List<string> GetGroups()
{
List<string> prodGroups = (from object item in lstProductGroups.SelectedItems select item.ToString()).ToList();
return prodGroups;
}
但是,如果嘗試從另一個線程訪問相同的方法,則會在列表中獲得所有名為System.Data.DataRowView
。
我什至使用BeginInvoke
在foreach
循環中嘗試了此方法,但item.ToString()
始終返回System.Data.DataRowView
。
我是Winforms線程技術的新手。 我究竟做錯了什么?
首先聲明一個委托:
delegate List<string> GetItemsDlg();
像這樣更改您的方法:
List<string> GetGroups() {
if (lstProductGroups.InvokeRequired) {
var dlg = new GetItemsDlg(GetGroups);
return lstProductGroups.Invoke(dlg) as List<string>;
}
List<string> prodGroups = (from object item in lstProductGroups.SelectedItems select item.ToString()).ToList();
return prodGroups;
}
調用您的方法:
List<string> items = GetGroups();
如何調用:
Invoke((MethodInvoker) delegate
{
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.