Reputation: 790
I have a ListView and a collection of ListViewItem. I simply want to insert all items in the collection at the top of the ListView.
Currently, I am doing it this way:
CollectionOfListViewItems.Sort(New CustomComparer(SortOrder.Descending))
For Each lvi As ListViewItem In CollectionOfListViewItems
TargetListView.Items.Insert(0, lvi)
Next
Since every insert operation will shift all items in the ListView, each insert operation will take O(n) time which seems like a bit of a waste.
Is there a better way of going about the same? Note that I know about InsertRange()
but unfortunately, that method is not available for the collection ListView.Items
.
Upvotes: 2
Views: 360
Reputation: 19641
Whether you're appending or inserting items, whenever you're making a large change to the ListView, you should always call BeginUpdate()
before making the changes and then EndUpdate()
after. This will prevent the ListView from visually updating its items (which is the part that takes the most time).
Your code should look something like this:
TargetListView.BeginUpdate()
For Each lvi As ListViewItem In CollectionOfListViewItems
TargetListView.Items.Insert(0, lvi)
Next
TargetListView.EndUpdate()
Prevents the control from drawing until the
EndUpdate()
method is called.
Upvotes: 3