Home > Software engineering >  How to filter a specific record from BindingList c#
How to filter a specific record from BindingList c#

Time:11-21

I have a bindinglist and after populating it, the list will be bind to a listbox.

private BindingList<VersionControlLabel> allTfsLabelList = new BindingList<VersionControlLabel>(); 

Versioncontrollabel class contains Name,version no, modified date etc..

Current implementation is when loading the form all the versions are load into the listbox then we have go through every item to find the specific one. Instead I want to add a textbox and when I type I want to show the record which has a exesiting word in textbox.

enter image description here

if user type the version number continuously the listbox should show the matching record

As enumrator properties are not available when I use the linq. How to do this?

I implemented something like this. But its not working. its not linq

        private void txtSearchLabel_KeyUp(object sender, KeyEventArgs e)
    {
        if (!string.IsNullOrEmpty(txtSearchLabel.Text))
        {
            string text = txtSearchLabel.Text;

            foreach (VersionControlLabel part in allTfsLabelList)
            {
                if(part.LabelId.ToString().Contains(text))
                {
                    lstLabels.DataSource = part;
                }
                else
                {
                    lstLabels.DataSource = allTfsLabelList;
                }
            }
           
        }
    }

CodePudding user response:

If you want to just do ad hoc filtering then you can do something like this:

private List<string> allItems = new List<string>();

private void DisplayFilteredList()
{
    var searchText = textBox1.Text.Trim();

    listBox1.DataSource = searchText.Length == 0
                              ? allItems
                              : allItems.Where(s => s.Contains(searchText)).ToList();
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    DisplayFilteredList();
}
  • Related