Trey Balut
Trey Balut

Reputation: 1395

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]);

Upvotes: 1

Views: 905

Answers (4)

Reza Aghaei
Reza Aghaei

Reputation: 125302

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);
}

Upvotes: 5

Ashkan Mobayen Khiabani
Ashkan Mobayen Khiabani

Reputation: 34180

for(int i = HomeTeamListBox.Items.Count-5; i>=0; i--)
{
    HomeTeamListBox.Items.RemoveAt(i);
}

Upvotes: 0

Kosala W
Kosala W

Reputation: 2143

This should work for you;

if(HomeTeamListBox.Items.Count > 5)
{
    var lastIndex = HomeTeamListBox.Items.Count - 5; 
    for(int i=0; i < lastIndex; i++)
    {
       HomeTeamListBox.Items.RemoveAt(i);
    }
}

Upvotes: 0

Michael
Michael

Reputation: 749

Your index i is going to increase by one each time it loops, but you are going to be removing an element each time you loop. What you want to do is remove each element at index 0 for the first 5 passes. So using your current For Loop

HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[0]);

Is what you want in the body.

Upvotes: 0

Related Questions