Removing ListView items

R

Ray Mitchell

Hello,


In my application I need to periodically remove all current items from a
ListView and add a new set into it. The following abbreviated code contains
the basic idea:


private void FillListViewFromFile(string path)
{
// listView = new ListView();
// listView.Clear();
for (int ix = listView.Items.Count - 1; ix >= 0; --ix)
listView.Items.RemoveAt(ix);


string line;
while ((line = sr.ReadLine()) != null)
{
// ...use Split to put fields into result array, etc...
string[] result;


// Add "result" array item to ListView
listView.Items.Add(new ListViewItem(result));
}
}


The problem is with properly removing all the items. I finally resorted to
the "for" loop shown to remove them one at a time from the bottom up, and it
all works perfectly. But it doesn't seem that this is the most elegant way
to do it. However, when I try either of the two techniques that I've
commented out, the ListView always displays as empty after adding the new
items. Can you please explain why and what I need to do to get them to work
correctly?


Thanks,
Ray
 
P

Pavel Minaev

Hello,

In my application I need to periodically remove all current items from a
ListView and add a new set into it.  The following abbreviated code contains
the basic idea:

      private void FillListViewFromFile(string path)
      {
//         listView = new ListView();
//         listView.Clear();
         for (int ix = listView.Items.Count - 1; ix >= 0; --ix)
            listView.Items.RemoveAt(ix);

         string line;
         while ((line = sr.ReadLine()) != null)
         {
            // ...use Split to put fields into result array, etc...
            string[] result;

            // Add "result" array item to ListView
            listView.Items.Add(new ListViewItem(result));
         }
      }

The problem is with properly removing all the items.  I finally resorted to
the "for" loop shown to remove them one at a time from the bottom up, andit
all works perfectly.  But it doesn't seem that this is the most elegantway
to do it.  However, when I try either of the two techniques that I've
commented out, the ListView always displays as empty after adding the new
items.  Can you please explain why and what I need to do to get them towork
correctly?  

ListView.Clear removes all items and _all columns_ from the list view.
What you need here is listView.Items.Clear().

On a side note, when you do this sort of thing, it helps to use
ListView.BeginUpdate() and ListView.EndUpdate() to speed things up a
bit, and avoid flicker if the list view is visible.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top