0
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

Edited by mike_2000_17: Fixed formatting

4
Contributors
5
Replies
9
Views
6 Years
Discussion Span
Last Post by ddanbe
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.

0

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]);
        }
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.

Can you show me an example please?

1

This was tested and works:

private void button1_Click(object sender, EventArgs e)
        {
            while (listBox1.SelectedItems.Count > 0)
            {
                listBox1.Items.Remove(listBox1.SelectedItem);
            }
        }
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.