How to removie multiple items from list box
private void btnCencelProducts_Click(object sender, EventArgs e)
{
for (int i = 0; i < lbFinalList.Items.Count; i++)
{
if (lbFinalList.GetSelected(i))
{
lbFinalList.Items.Remove(lbFinalList.Items[i]);
}
}
}
thats code of my button i have list box where i want to removie multible item..
when i chose more than one item so only 2 or often 1 item is removing not all the items are removing which was selected...
Regards...
Farhad
Farhad.idrees
Junior Poster in Training
63 posts since Dec 2010
Reputation Points: 11
Solved Threads: 0
When you remove an item (or add one) to a list it messes up the Selected values. You can't rely on them being valid anymore. What you need to do is copy the selected values somewhere else then use that new copy to remove the items.
Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
Try using SelecredIndices collection:
public Form1()
{
InitializeComponent();
//my test population:
char[] array = "abcdef".ToCharArray();
for (int i = 0; i < array.Length; i++)
listBox1.Items.Add(array[i]);
listBox1.SelectionMode = SelectionMode.MultiExtended;
}
private void button1_Click(object sender, EventArgs e)
{
while (listBox1.SelectedIndices.Count > 0)
listBox1.Items.RemoveAt(listBox1.SelectedIndices[0]);
}
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
SelectedIndices makes it worse, as each time you remove an item the Indices change.
Momerath
Nearly a Senior Poster
3,386 posts since Aug 2010
Reputation Points: 1,232
Solved Threads: 558
When you remove an item (or add one) to a list it messes up the Selected values. You can't rely on them being valid anymore. What you need to do is copy the selected values somewhere else then use that new copy to remove the items.
Can you show me an example please?
Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
This was tested and works:
private void button1_Click(object sender, EventArgs e)
{
while (listBox1.SelectedItems.Count > 0)
{
listBox1.Items.Remove(listBox1.SelectedItem);
}
}
ddanbe
Senior Poster
3,829 posts since Oct 2008
Reputation Points: 2,070
Solved Threads: 661