Correction in the following delegate and method for invoking a control

174 Views Asked by At

I need to access a listview's items in a DoWork event handler. For this the delegate and the method to invoke the listview what I wrote is:

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;
       }
   }

This is the first time I am working with invoking a control. So please let me know where I am wrong. One error that I get is gsm_modem.Form1.getItems(System.Windows.Forms.ListView): not all code paths return a value. I even guess that what I wrote might be wrong. Correction please..

2

There are 2 best solutions below

1
On BEST ANSWER

Thanks to @Ravi patel for the idea. This is what I did to solve the problem:

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
}

Then used listItems in my other thread easily.

0
On

You can do something like this

First create shared variable in global scope for your form.

List<string> listItems;

Now before calling RunWorkerAsync do following

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();

Now read the list inside background worker using foreach.