What actually is taking so much time? Is it your loop itself (I do believe 30000 iterations last not that long) or are there additional actions slowing the process? You could try to disable event handlers (ItemSelectionChanged and the like, all that may be triggered by selection) or call SuspendLayout()/ResumeLayout() methods before and after selection. Also, if you really have to deal with 30000 items, consider using listview in virtual mode
Disabling event handlers is easy: for example, you do have ItemSelectionChanged handler, listView1_SelectedIndexChanged on your listview, listView1. Then selection logic should look like that:
listView1.SelectedIndexChanged-=listView1_SelectedIndexChanged;
try
{
}
finally
{
listView1.SelectedIndexChanged+=new EventHandler(listView1_SelectedIndexChanged);
}
Try/catch block is not necessary, it's added simply to ensure event handler will be restored no matter what, even after exception in loop. If there are more handlers, ItemSelectionChanged, for example, just disable and restore them in the same manner.
Working with layout events suspending is simple as well. Improving previous block of code:
listView1.SelectedIndexChanged-=listView1_SelectedIndexChanged;
listView1.SuspendLayout();
try
{
}
finally
{
listView1.SelectedIndexChanged+=new EventHandler(listView1_SelectedIndexChanged);
listView1.ResumeLayout();
}
Finally, placing listview in virtual mode doesn't even require code :). You can do it from Property Editor, setting VirtualMode property to
true (by default it's
false). Working with listview this way is harder, though: you have to implement RetrieveVirtualItem event handler and provide VirtualListSize property; also you cannot use Items/SelectedItems collections. There are other limitations as well (see
here), so you should decide yourself whether virtual mode suits your project