Search code examples
c#.netwinformslistbox-control

Keep last N items and remove other items from ListBox


I have a C# Winform with a ListBox. I am trying to remove all the items except the last 5 items. The ListBox sort is set to Ascending.

The items in the ListBox look like the following:

2016-3-1
2016-3-2
2016-3-3
2016-3-4
...
2016-03-28

Here is my code to remove the beginning items.

for (int i = 0; i < HomeTeamListBox.Items.Count - 5; i++)
{
    try
    {
        HomeTeamListBox.Items.RemoveAt(i);
    }
    catch { }
}

I've also tried HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[i]);


Solution

  • While there are more than n items in the list, you should remove items from start of the list.
    This way you can keep the last n items of ListBox:

    var n = 5; 
    while (listBox1.Items.Count > n)
    {
        listBox1.Items.RemoveAt(0);
    }