以下委托中的更正和调用控件的方法

时间:2012-08-18 08:41:23

标签: c# delegates invokerequired

我需要在DoWork事件处理程序中访问listview的项目。为此,委托和调用listview的方法是我写的:

delegate ListView itemDelegate(ListView bufferedListView1);

   private ListView getItems(ListView bufferedListView1)
   {
       if (bufferedListView1.InvokeRequired)
       {
         //  BeginInvoke(new itemDelegate(getItems));
             bufferedListView1.Invoke(new itemDelegate(getItems));
       }
       else
       {
           return bufferedListView1;
       }
   }

这是我第一次使用调用控件。所以,请让我知道我错在哪里。我得到的一个错误是gsm_modem.Form1.getItems(System.Windows.Forms.ListView): not all code paths return a value。我甚至猜测我写的东西可能是错的。请更正..

2 个答案:

答案 0 :(得分:2)

你可以做这样的事情

首先在表单的全局范围内创建共享变量。

List<string> listItems;

现在,在调用RunWorkerAsync之前,请执行以下操作

listItems = new List<string>();
foreach (ListViewItem item in bufferedListView1.Items)
            {
                //If you want to add tag to list then you can use dictionary like Dictionary<string, object) listItems; and then add items as listItems.Add(item.Text, item.Tag); It only works if text is unique.
                listItems.Add(item.Text);
            }
bgw1.RunWorkerAsync();

现在使用foreach读取后台worker中的列表。

答案 1 :(得分:0)

感谢@Ravi patel的想法。这就是我为解决问题所做的工作:

ListView listItems = new ListView();\\In global scope

foreach (ListViewItem item in bufferedListView1.Items)
{
   listItems.Items.Add((ListViewItem)item.Clone()); // Copied the bufferedListview's items that are to be accessed in other thread to another listview- listItems
}

然后在我的其他线程中轻松使用listItems。