Tre*_*lut 1 .net c# listbox-control winforms
我有一个带有ListBox的C#Winform.我试图删除除最后5项之外的所有项目.ListBox排序设置为Ascending.
ListBox中的项目如下所示:
2016-3-1
2016-3-2
2016-3-3
2016-3-4
...
2016-03-28
Run Code Online (Sandbox Code Playgroud)
这是我删除开头项目的代码.
for (int i = 0; i < HomeTeamListBox.Items.Count - 5; i++)
{
try
{
HomeTeamListBox.Items.RemoveAt(i);
}
catch { }
}
Run Code Online (Sandbox Code Playgroud)
我也试过了 HomeTeamListBox.Items.RemoveAt(HomeTeamListBox.Items[i]);
虽然n
列表中有多个项目,但您应该从列表的开头删除项目.
这样你可以保留最后的n
项目ListBox
:
var n = 5;
while (listBox1.Items.Count > n)
{
listBox1.Items.RemoveAt(0);
}
Run Code Online (Sandbox Code Playgroud)