Listbox控件在每次删除完选定的项后都是重新更新项索引。如果程序思路是从索引0开始循环删除选定的项,就不能达到程序要求,由于删除一个,后面的项索引就会减一。明白了这个原理之后,我们可以从最后得索引往前搜索,就不会出问题了。
方法1(从网上搜的)
void Btn_DeleteClick(object sender, System.EventArgs e)
{
ListBox.SelectedIndexCollection indices =this.listBox1.SelectedIndices;
int selected=indices.Count;
if(indices.Count>0)
{
for(int n=selected -1;n>=0;n--)
{
int index =indices[n];
listBox1.Items.RemoveAt(index);
}
}
}
方法2(自己写的)
void Btn_DeleteClick(object sender, System.EventArgs e)
{
for(int i=this.listBox1.Items.Count-1;i>=0;i--)
{
this.listBox1.Items.Remove(this.listBox1.SelectedItem);
}
}