Burhan
Burhan

Reputation: 790

How to efficiently insert multiple rows at the start of a ListView?

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

Answers (1)

41686d6564
41686d6564

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()

References:

Upvotes: 3

Related Questions