By default, The ListBox control can only be selected. To select multiple items, you must set the SelectionMode attribute to SelectionMode. MultiSimple.
How can I capture this information if I want to delete multiple items selected by ListBox or perform other operations?
Private void button_deleteSelected_Click (object sender, EventArgs e)
{
ListBox. SelectedIndexCollection sic = listBox_demo.SelectedIndices; // obtain the subscript of the selected Item
If (sic. Count = 0)
Return;
Else
{
// Put the selected Item in the list
List <int> list = new List <int> ();
For (int I = 0; I <sic. Count; I ++)
{
List. Add (sic [I]);
}
List. Sort (); // Sort the list (the default sorting result in the library generally refers to sorting from bottom to big)
While (list. Count! = 0) // Delete the selected Item from The ListBox control in the ascending order of the subscript
// If other sequence is used here, the validity of the lower mark may be damaged.
{
ListBox_demo.Items.RemoveAt (list [list. Count-1]);
List. RemoveAt (list. Count-1 );
}
}
}
One method is simpler:
While (listBox1.SelectedItems. Count! = 0)
{
ListBox1.Items. RemoveAt (listBox1.SelectedIndices [0]);
}
While (listBox1.SelectedItems. Count! = 0)
{
ListBox1.Items. RemoveAt (listBox1.SelectedIndices [0]);
}