简体   繁体   中英

How do i make a search bar for a listbox?

So, what I am trying to accomplish is that through a textbox (searchTxt) I can get a listbox (lbRooms) to narrow down and remove the items it has, to fit the criteria of the text in the search box, but then when the text of the search bar is null/you delete some of the text in it, I would like the items to come back. I have tried making a List roomList:

    public List<string> roomList = new List<string>();

And whenever an item is added to the listbox, add it to the list, and then i tried:

    private void searchTxt_TextChanged(object sender, EventArgs e)
    {
        for (int i = 0; i < lbRooms.Items.Count; i++)
        {
            string s = lbRooms.Items[i].ToString();
            if (!s.Contains(searchTxt.Text))
            {
                lbRooms.Items.RemoveAt(i);
            }
            else
            {
                if (!lbRooms.Items.Contains(roomList[i]))
                {
                    lbRooms.Items.Add(roomList[i]);
                }
            }
        }
    }

But that does not seem to work.

You could reference System.Linq and try:

if (!lbRooms.Items.Any(l => l == searchTxt.Text))
    lbRooms.Items.Add(searchTxt.Text);

That'd add characters as they're typed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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