Reputation:
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.
Upvotes: 0
Views: 1350
Reputation: 2134
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;
}
}
Upvotes: 0
Reputation: 8079
You will have to do this manually:
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);
}
Upvotes: 1