简体   繁体   English

文本框更改时如何从列表框中消除项目

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

I wanna make a small code block about c #. 我想做一个关于C#的小代码块。

first think a listbox with elements. 首先考虑一个带有元素的列表框。 then think a blank textbox. 然后考虑一个空白的文本框。

when I write a letter to textbox(dont think just letter, think about a word ,I split it with textbox1_textchanged ),if an element dont have the word it must be deleted from listbox. 当我给文本框写一封信时(不要只想字母,请考虑一个单词,我用textbox1_textchanged拆分了它),如果某个元素没有单词,则必须从列表框中删除它。

example: 例:

here are listbox elements : 这是列表框元素:

abraham
michael
george
anthony

when i type "a",I want michael and george to be deleted,then when I type "n" I want abraham to be deleted(at this point total string is "an")... 当我输入“ a”时,我要删除迈克尔和乔治,然后当我输入“ n”时,我要删除亚伯拉罕(此时总字符串为“ an”)...

Thanks by now (: 现在谢谢(:

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

You could try something like this. 您可以尝试这样的事情。 It will match what you have in the textbox and remove what doesn't match. 它将匹配您在文本框中的内容,并删除不匹配的内容。

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
            }

        }

    }
}

You can filter the items that doesn't contain the text and remove them from the listbox: 您可以过滤不包含文本的项目并将其从列表框中删除:

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