简体   繁体   English

如果项目存在于另一个ListBox中,则从ListBox中删除项目

[英]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. 我试图从ListBox中删除数字项,如果这些值存在于另一个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). ListBox1由Array填充,而ListBox2由DataSet表(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. 另请参考:我不是将项目添加到列表框中,也不是选择...只是要比较这两个项目,如果它们全部自动存在,则只需按一下按钮即可将它们从ListBox1中删除。 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) { 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. 但是,这会导致错误,因为您在迭代它的项目时修改了ListBox 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 @D斯坦利

Thank you for your help and explanation. 感谢您的帮助和解释。 @Yuriy - Thank you for the clarification, the @Yuriy - 谢谢你的澄清,

i >= 0 我> = 0

works great. 效果很好。 I also converted to listbox to int32. 我也将列表框转换为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);
            }
        }

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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