I am adding items to a ListView like this:
private int AddThreadToListView(int threadNumber, string proxy, string query, string page, string links)
{
int index = 0;
listView1.SuspendLayout();
Invoke(new MethodInvoker(
delegate
{
string[] row1 = { proxy, query, page, links };
ListViewItem item = new ListViewItem();
listView1.Items.Add(threadNumber.ToString()).SubItems.AddRange(row1);
index = listView1.Items.Count - 1;
}
));
if ((listView1.Items.Count % 1000) == 0)
{
listView1.ResumeLayout();
listView1.SuspendLayout();
}
listView1.ResumeLayout();
return index;
}
I then keep track of the item Index so i can go back and update it from within my threads. (That works great).
The problem however is when i start to remove these items, for some reasons the index changes..
Here are my update and remove methods:
private void UpdateThreadListView(int threadNumber, string proxy, string query, string page, string links)
{
Invoke(new MethodInvoker(
delegate
{
listView1.BeginUpdate();
ListViewItem itm = listView1.Items[threadNumber];
itm.SubItems[1].Text = proxy;
itm.SubItems[2].Text = query;
itm.SubItems[3].Text = page;
itm.SubItems[4].Text = links;
listView1.EndUpdate();
}
));
}
private void RemoveThreadListView(int threadNumber)
{
Invoke(new MethodInvoker(
delegate
{
listView1.BeginUpdate();
listView1.Items[threadNumber].Remove();
listView1.EndUpdate();
}
));
}
I somehow need an index that does not change, a unique one for each listview item created..
How could i accomplish this?
The
Indexis managed automatically; it represents the location of a given item in the list, so if you remove an item, the position of all subsequent items will change.You could use the
Tagproperty of theListViewItemas a key to search for items using other criteria; e.g.Tagcan be set to any object you wish; it’s there essentially for this very purpose (uniquely identifying nodes by means other than the index).Note that this will be less efficient than finding elements using the index, since it’s worst-case
O(n)(as opposed toO(1)for indexing).EDIT:
The above method is just an example of how to find an item given with a given tag. You can set the tag whenever you want, but in general you’ll probably want to set it when you create the list view item, e.g.
Then, assuming you implemented a
FindItem()like I gave an example of above, you could do this:which in this example would return the item for thread #3.