嘗試遍歷列表框然后刪除項(xiàng)目時(shí),出現(xiàn)以下錯(cuò)誤。此枚舉器綁定到的列表已被修改。如果列表不變,則只能使用枚舉數(shù)。foreach (string s in listBox1.Items){ MessageBox.Show(s); //do stuff with (s); listBox1.Items.Remove(s);}如何刪除該項(xiàng)目并仍然在其中循環(huán)瀏覽?
3 回答

吃雞游戲
TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超7個(gè)贊
您要?jiǎng)h除所有項(xiàng)目嗎?如果是這樣,foreach請(qǐng)先執(zhí)行此操作,然后再使用Items.Clear()刪除所有這些。
否則,也許由索引器向后循環(huán):
listBox1.BeginUpdate();
try {
for(int i = listBox1.Items.Count - 1; i >= 0 ; i--) {
// do with listBox1.Items[i]
listBox1.Items.RemoveAt(i);
}
} finally {
listBox1.EndUpdate();
}

達(dá)令說(shuō)
TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
這是我的解決方案,無(wú)需后退且沒(méi)有臨時(shí)列表
while (listBox1.Items.Count > 0)
{
string s = listBox1.Items[0] as string;
// do something with s
listBox1.Items.RemoveAt(0);
}
- 3 回答
- 0 關(guān)注
- 359 瀏覽
添加回答
舉報(bào)
0/150
提交
取消