簡體   English   中英

文本框更改時如何從列表框中消除項目

[英]How to eliminate items from listbox when textbox changed

我想做一個關於C#的小代碼塊。

首先考慮一個帶有元素的列表框。 然后考慮一個空白的文本框。

當我給文本框寫一封信時(不要只想字母,請考慮一個單詞,我用textbox1_textchanged拆分了它),如果某個元素沒有單詞,則必須從列表框中刪除它。

例:

這是列表框元素:

abraham
michael
george
anthony

當我輸入“ a”時,我要刪除邁克爾和喬治,然后當我輸入“ n”時,我要刪除亞伯拉罕(此時總字符串為“ an”)...

現在謝謝(:

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        for (int i = 0; i < listBox1.Items.Count; i++)
        {
            string item = listBox1.Items[i].ToString();
            foreach(char theChar in textBox1.Text)
            {
                if(item.Contains(theChar))
                {
                    //remove the item, consider the next list box item
                    //the new list box item index would still be i
                    listBox1.Items.Remove(item);
                    i--;
                    break;
                }
            }
        }
    }

您可以嘗試這樣的事情。 它將匹配您在文本框中的內容,並刪除不匹配的內容。

private void textBox1_TextChanged(object sender, EventArgs e)
{
    for (int i = 0; i < listBox1.Items.Count ; i++)
    {
        for (int j = 0; j < textBox1.Text.Length  ; j++)
        {
            if (textBox1.Text[j] != listBox1.Items[i].ToString()[j])
            {
                if (i < 0) break;
                listBox1.Items.RemoveAt(i);
                i = i - 1; // reset index to point to next record otherwise you will skip one
            }

        }

    }
}

您可以過濾不包含文本的項目並將其從列表框中刪除:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    var itemsToRemove = listBox1.Items.Cast<object>().Where(x => !x.ToString().Contains(textBox1.Text)).ToList();
    foreach(var item in itemsToRemove)
        listBox1.Items.Remove(item);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM