ListBox控制項怎樣刪除選擇的多個Item(c#)

來源:互聯網
上載者:User
今天到一個網友哥們秒大刀(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]);
        } 
     }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.