2
votes

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);
        }
    }
}
2
I think it's a simple typo foreach (int item in listBox1.Items) try listBox2.Items.Yurii
just caught that...it was just a type on the forum but my code actually has listbox2.items...I just updated the code here. still no luck.goodfella
try evaluating your if statement to explicitly check for truerommel

2 Answers

5
votes

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);
    }
}
2
votes

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

    }