Filter ListBox with TextBox in realtime

35,803

It's hard to deduct just from the code, but I presume your filtering problem born from the different aspects:

a) You need a Model of the data shown on ListBox. You need a colleciton of "Items" which you hold somewhere (Dictionary, DataBase, XML, BinaryFile, Collection), some kind of Store in short.

To show the data on UI you always pick the data from that Store, filter it and put it on UI.

b) After the first point your filtering code can look like this (a pseudocode)

var registrationsList = DataStore.ToList(); //return original data from Store

registrationListBox.BeginUpdate();
registrationListBox.Items.Clear();

if(!string.IsNullOrEmpty(SrchBox.Text)) 
{
  foreach (string str in registrationsList)
  {                
     if (str.Contains(SrchBox.Text))
     {
         registrationListBox.Items.Add(str);
     }
  }
}
else 
   registrationListBox.Items.AddRange(registrationsList); //there is no any filter string, so add all data we have in Store

registrationListBox.EndUpdate();

Hope this helps.

Share:
35,803
observ
Author by

observ

Updated on January 30, 2020

Comments

  • observ
    observ over 4 years

    I am trying to filter an listbox with text from a textbox, realTime.

    Here is the code:

    private void SrchBox_TextChanged_1(object sender, EventArgs e)
    {
      var registrationsList = registrationListBox.Items.Cast<String>().ToList();
      registrationListBox.BeginUpdate();
      registrationListBox.Items.Clear();
      foreach (string str in registrationsList)
      {
        if (str.Contains(SrchBox.Text))
        {
          registrationListBox.Items.Add(str);
        }
      }
      registrationListBox.EndUpdate();
    }
    

    Here are the issues:

    1. When I run the program i get this error: Object reference not set to an instance of an object

    2. If I hit backspace, my initial list is not shown anymore. This is because my actual list of items is now reduced, but how can I achieve this?

    Can you point me in the right direction?