今天到一個網友哥們秒大刀(http://dearymz.blog.163.com)哪兒看部落格,看到他把我問他的問題給寫成了部落格,並在文章最後送給我一個祝福,我很是感動。我是那種受了別人的好就感激涕零的人,所以在這兒也祝他一切順利。
下面是秒大刀給我解決辦法:
ListBox控制項預設情況下只可以進行單選,如要進行多選操作,需要將SelectionMode屬性設定成SelectionMode.MultiSimple。
如果需要將ListBox選擇的多項Item刪除,或要進行其它的操作該怎樣捕獲這些資訊呢?
private void button_deleteSelected_Click(object sender, EventArgs e)
{
ListBox.SelectedIndexCollection sic = listBox_demo.SelectedIndices;//得到選擇的Item的下標
if (sic.Count == 0)
return;
else
{
// 將選擇的Item放入list中
List<int> list = new List<int>();
for (int i = 0; i < sic.Count; i++)
{
list.Add(sic[i]);
}
list.Sort();//對list進行排序(庫裡預設的排序結果一般指的是從下到大的排序)
while(list.Count != 0)//按照下標從大到小的順序從ListBox控制項裡刪除選擇的Item
//如果這裡採用其它順序則可能破壞下標的有效性
{
listBox_demo.Items.RemoveAt(list[list.Count - 1]);
list.RemoveAt(list.Count - 1);
}
}
}
下面是我作為初學者用的簡單方法:
protected void remove1_Click(object sender, EventArgs e)
{
for (int m = 0; m < ListBox2.Items.Count; m++)
{
if (ListBox2.Items[m].Selected)
ListBox2.Items.Remove(ListBox2.Items[m]);
}
}