Search code examples
c#winformstextboxlistboxletter

How to eliminate items from listbox when textbox changed


I wanna make a small code block about 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.

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")...

Thanks by now (:


Solution

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