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

Recommended Answers

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.

Jump to Post

This was tested and works:

private void button1_Click(object sender, EventArgs e)
        {
            while (listBox1.SelectedItems.Count > 0)
            {
                listBox1.Items.Remove(listBox1.SelectedItem);
            }
        }
Jump to Post

All 5 Replies

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.

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

SelectedIndices makes it worse, as each time you remove an item the Indices change.

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?

This was tested and works:

private void button1_Click(object sender, EventArgs e)
        {
            while (listBox1.SelectedItems.Count > 0)
            {
                listBox1.Items.Remove(listBox1.SelectedItem);
            }
        }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.19 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.