简体   繁体   中英

How to remove / filter data on listbox using textbox on C#

I need to add a search box to a listbox that has data pulling from SQL - I'm not sure how as it isn't my code. I just need to add the search function. The listbox holds user names and surnames. So all I have to work with is lbUsers (the listbox name).

Thus far I have it to search a user name but it's only displaying the closest search - I want the code to filter out everything containing what I have typed into the search box:

    private void btnSearch_Click(object sender, EventArgs e)
    {
        this.lbUsers.SelectedItems.Clear();
        for (int s = this.lbUsers.Items.Count - 1; s >= 0; s--)
        {
            if (this.lbUsers.Items[s].ToString().ToLower().Contains(this.tbSearch.Text.ToLower()))
            {
                this.lbUsers.SetSelected(s, true);
            }
        }
    }

I also don't want all the users to display - only those relating to the search box's criteria.

You will have to do this manually:

  • Save all users in a list
  • Filter the list accoring the text in the TextBox
  • Add the results to the ListBox

This is a minimal example:

List<User> users = new List<User>();

private void txtFilter_TextChanged(object sender, EventArgs e)
{
    List<User> displayList = this.users;

    if(this.txtFilter.Text != string.Empty)
    {
        displayList = this.users.Select(u => u.Name == this.txtFilter.Text);
    }

    this.lbUsers.Items.Clear();
    this.lbUsers.Items.AddRange(displayList);
}

I think the best way to do this is through visibility. This way you don't have to keep creating/disposing of listbox items.

For example, the code below would do what you want:

foreach (var item in lbUsers.Items)
{
    if (item.ToString().Contains(this.tbSearch.Text))
    {
        item.Visible = true;
    }
    else
    {
        item.Visible = false;
    }
}

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