private void button2_Click(object sender, EventArgs e)
{
int b = listBox_1.SelectedItems.Count;//获取要删除项的个数
for (int i = b-1; i >= 0; i--)//设立循环一个一个的删除
{
int a = listBox_1.SelectedIndex;//获取要删除项的索引
listBox_1.Items.RemoveAt(a);//根据索引删除第一个项直到最后一个项被删除
}
}
if (listBox1.Items[i].selected)
this.listBox1.Items.RemoveAt(i);
} 这样明显有问题 你item里面有10个元素 你删了3个 还有几个? remove 1之后 原来的2就变成了1 原来的1被移除了 你在移除2 就是移除的是3
ListBox a1 = new ListBox();
object[] selected_objs = new object[a1.SelectedItems.Count];
a1.SelectedItems.CopyTo(selected_objs, 0);
foreach (object oval in selected_objs)
{
a1.Items.Remove(oval);
}
按我写的这样弄吧
方法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);
}
}
for (int i = listBox1.SelectedItems.Count - 1; i >= 0; i--)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
for(int i=listBox1.Items.Count-1;i>=0;i--){
if(listBox1.Items[i].Selected)
listBox1.Items.RemoveAt(i);
}