Search code examples
.netlistviewitem

How to use a listview of UI thread in DoWork event handler?


I have listview on the UI thread. I have some operations to be performed through the background worker's DoWork event handler since they are time consuming. But I cant acess the listview items in my DoWork handler since it raises an exception:Cross-thread operation not valid: Control 'bufferedListView1' accessed from a thread other than the thread it was created on.

So how do I acess my bufferedlistview in my DoWork event handler. This is the code to be handled in DoWork:

foreach (ListViewItem item in bufferedListView1.Items) 
{ 
    string lname = bufferedListView1.Items[i].Text; 
    string lno = bufferedListView1.Items[i].SubItems[1].Text; 
    string gname = bufferedListView1.Items[i].SubItems[2].Text; 
    string line = lname + "@" + lno + "@" + gname; 
    if (gname.Contains(sgroup)) 
    { 
        var m = Regex.Match(line, @"([\w]+)@([+\d]+)@([\w]+)"); 
        if (m.Success) 
        { 
            port.WriteLine("AT+CMGS=\"" + m.Groups[2].Value + "\""); 
            port.Write(txt_msgbox.Text + char.ConvertFromUtf32(26)); 
            Thread.Sleep(4000); 
        } 
        sno++; 
    } 
    i++; 
}

Solution

  • All I wanted was to read the listview in UI thread in other thread. All the solutions given were using invoke method but I found a rather easy way to do this:

    ListView lvItems = new ListView(); \\in global scope
    

    At the required location in my code:

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

    Then used the lvItems listview in my DoWork event handler. Simple n Easy :)