作者tylerfirst (......)
看板C_Sharp
标题[问题] C# 删除listbox中复数项的问题
时间Fri Oct 30 23:41:16 2009
※ [本文转录自 C_and_CPP 看板]
作者: tylerfirst (......) 看板: C_and_CPP
标题: [问题] C# 删除listbox中复数项的问题
时间: Fri Oct 30 23:27:22 2009
如题,小弟用C#想设计一个button
此button按下的同时,会将listbox中选取的项目删除
程式码如下:
private void button5_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex != -1)
{
foreach (int select_Index in listBox1.SelectedIndices)
{
listBox1.Items.RemoveAt(select_Index);
}
}
}
跑出来的结果很奇怪= ="
如果选两项,则只会删除index比较前面的
如果选两项以上,则会"隔项删除".....意思就是选第一,二,四项却只会删掉一,四项
怎麽出现这种怪现象啊orz
我有试过把RemoveAt拿掉,单纯用MessageBox显示抓到的项数,结果是正常的
有想过会不会因为是Remove的关系导致程式抓的Index乱掉...
请板上前辈们指点一下 3Q<(_ _)>
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 218.173.164.170
1F:→ tiyun:请至C_Sharp 10/30 23:37
2F:推 VictorTom:C#板在楼下啊XDDD 10/30 23:37
3F:→ tylerfirst:啊 抱歉XD 因为我的最爱都放在一起... 10/30 23:40
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 218.173.164.170
4F:→ liaommx:如果是因为remove的话,那为什麽1,2,4只删除1,4?..XD 10/30 23:52
5F:→ liaommx:为什麽不是删除1,5?:P 10/30 23:52
6F:→ tylerfirst:我也不知道= = 但是把remove拿掉又正常...我也只能想到 10/31 00:24
7F:→ tylerfirst:是remove的关系了... 10/31 00:24
8F:→ EricTsai:请用for,foreach不应该变动集合 10/31 00:25
9F:→ EricTsai:不过这样说好像没解决问题...Remove之後index的确就变了 10/31 00:28
10F:→ fphoenix923:你需要从後面删回来,因为删完後Index会重排 10/31 00:58
11F:→ tylerfirst:解决了! 非常感谢~ 10/31 08:55