I have a listView that is being updated from multiple threads, with the threads status and id being displayed. When a thread has ended the item is removed.
My problem is that the way i use to update my listView is by using the listViews ID (to locate the subitems i wish to update). Now, as listView items start getting removed i run into problems because that ID for a specific thread has changed..
Here is the code i currently use to update and remove:
private void AddToListViewThread(string user, string status, int threadNumber)
{
Invoke(new MethodInvoker(
delegate
{
listView2.BeginUpdate();
this.listView2.Items[threadNumber].SubItems[1].Text = user;
this.listView2.Items[threadNumber].SubItems[2].Text = status;
listView2.EndUpdate();
}
));
}
private void RemoveFromListViewThread(int threadNumber)
{
Invoke(new
MethodInvoker(
delegate
{
listView2.BeginUpdate();
this.listView2.Items.RemoveAt(threadNumber);
listView2.EndUpdate();
}
));
}
I now understand that i cannot use the threadNumber as the item index (as items get removed) is there any other way i could achieve this? maybe by targeting the “user” subitem? and then getting subitems from that?
Use the tag property of the ListViewItem to store a different index (similar to the SQL autoincrement ).
The Tag property is a field used to store metadata about the item.
A simple binary search would let you find the item to remove in Log(n) time.
Your code would looks like this: