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

怎甘沉沦 提交于 2020-01-30 08:12:11

问题


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.


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/44624932/how-to-remove-filter-data-on-listbox-using-textbox-on-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!