简体   繁体   中英

Remove items from ListBox if item exists in another ListBox

I am trying to remove numerical items from a ListBox if those values exist in another ListBox. My code does not seem to work and I could not locate any help online. ListBox1 is populated by Array and ListBox2 is populated from a DataSet table (fyi).

Also for reference: I'm not adding and items to a listbox or selecting...simply just want to compare both and remove ListBox2 items from ListBox1 if they exist all automatically with a press of a button. Thank you,

private void button1_Click(object sender, EventArgs e)
{
    foreach (int item in listBox1.Items)
    {
        if (listBox2.Items.Contains(item))
        {
            listBox1.Items.Remove(item);
        }
    }
}

Well you're only referencing one list box in your code - I suspect you would want:

private void button1_Click(object sender, EventArgs e) {

foreach (int item in listBox1.Items)
{
    if (listBox2.Items.Contains(item))   // notice change of reference
    {
        listBox1.Items.Remove(item);
    }
}

However that would cause an error since you're modifying the ListBox while you're iterating over it's items. One way to safely remove items it to iterate backwards over the colection:

for (int i = listBox1.Items.Count - 1; i >= 0; i--)
{
    int item = listBox1.Items[i];
    if (listBox2.Items.Contains(item))   // notice change of reference
    {
        listBox1.Items.RemoveAt(i);
    }
}

@D Stanley

Thank you for your help and explanation. @Yuriy - Thank you for the clarification, the

i >= 0

works great. I also converted to listbox to int32. Below is the fully working code:

    private void button1_Click(object sender, EventArgs e)
    {

        for (int i = listBox1.Items.Count - 1; i>= 0; i--)
        {
            int item = Convert.ToInt32(listBox1.Items[i]);
            if (listBox2.Items.Contains(item))
            {
                listBox1.Items.Remove(item);
            }
        }

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM