如何用C#一次刪除ListBox控件中選擇的多項? Listbox控件在每次刪除完選定的項后都是重新更新項索引。如果程序思路是從索引0開始循環(huán)刪除選定的項,就不能達到程序要求,由于刪除一個,后面的項索引就會減一。明白了這個原理之后,我們可以從最后得索引往前搜索,就不會出問題了。 方法1(從網(wǎng)上搜的) 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); } } |
|