简体   繁体   English

如何为列表框创建搜索栏?

[英]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. 因此,我要完成的工作是,通过文本框(searchTxt),我可以得到一个列表框(lbRooms),以缩小范围并删除其所包含的项,以适合搜索框中文本的条件,但是当搜索栏的文本为空/您删除了其中的一些文本,我希望这些项目回来。 I have tried making a List roomList: 我尝试过制作一个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: 您可以引用System.Linq并尝试:

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

That'd add characters as they're typed. 这会在键入字符时添加字符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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