如何用C#一次刪除ListBox控件中選擇的多項(xiàng)?
Listbox控件在每次刪除完選定的項(xiàng)后都是重新更新項(xiàng)索引。如果程序思路是從索引0開(kāi)始循環(huán)刪除選定的項(xiàng),就不能達(dá)到程序要求,由于刪除一個(gè),后面的項(xiàng)索引就會(huì)減一。明白了這個(gè)原理之后,我們可以從最后得索引往前搜索,就不會(huì)出問(wè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(自己寫(xiě)的)
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);
}
}
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶(hù)發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。