Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter ListBox with TextBox in realtime

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?

like image 302
observ Avatar asked Apr 02 '12 20:04

observ


1 Answers

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.

like image 113
Tigran Avatar answered Sep 23 '22 18:09

Tigran