我有一个带有ListBox的C#Winform。我试图删除除最后5项之外的所有项目。 ListBox排序设置为升序。
ListBox中的项目如下所示:
2016-3-1
2016-3-2
2016-3-3
2016-3-4
...
2016-03-28
这是删除开头项目的代码。
for (int i = 0; i < HomeTeamListBox.Items.Count - 5; i++)
{
try
{
HomeTeamListBox.Items.RemoveAt(i);
}
catch { }
}
我也试过HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[i]);
答案 0 :(得分:5)
虽然列表中有多个n
个项目,但您应该从列表的开头删除项目
这样,您就可以保留n
的最后ListBox
项:
var n = 5;
while (listBox1.Items.Count > n)
{
listBox1.Items.RemoveAt(0);
}
答案 1 :(得分:0)
你的索引每次循环时都会增加1,但每次循环时你都会删除一个元素。你想要做的是删除前5个传球的索引0处的每个元素。所以使用你当前的For Loop
HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items [0]);
你想要的是身体。
答案 2 :(得分:0)
这对你有用;
if(HomeTeamListBox.Items.Count > 5)
{
var lastIndex = HomeTeamListBox.Items.Count - 5;
for(int i=0; i < lastIndex; i++)
{
HomeTeamListBox.Items.RemoveAt(i);
}
}
答案 3 :(得分:0)
for(int i = HomeTeamListBox.Items.Count-5; i>=0; i--)
{
HomeTeamListBox.Items.RemoveAt(i);
}