簡體   English   中英

如果項目存在於另一個ListBox中,則從ListBox中刪除項目

[英]Remove items from ListBox if item exists in another ListBox

我試圖從ListBox中刪除數字項,如果這些值存在於另一個ListBox中。 我的代碼似乎不起作用,我找不到任何在線幫助。 ListBox1由Array填充,而ListBox2由DataSet表(fyi)填充。

另請參考:我不是將項目添加到列表框中,也不是選擇...只是要比較這兩個項目,如果它們全部自動存在,則只需按一下按鈕即可將它們從ListBox1中刪除。 謝謝,

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

好吧,您只引用代碼中的一個列表框-我懷疑您會想要:

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

但是,這會導致錯誤,因為您在迭代它的項目時修改了ListBox 一種安全刪除項目的方法,以使其在集合上向后迭代:

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斯坦利

感謝您的幫助和解釋。 @Yuriy - 謝謝你的澄清,

我> = 0

效果很好。 我也將列表框轉換為int32。 以下是完整的工作代碼:

    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