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:
-
When I run the program i get this error:
Object reference not set to an instance of an object -
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?
It’s hard to deduct just from the code, but I presume your filtering problem born from the different aspects:
a) You need a
Modelof the data shown onListBox. 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)
Hope this helps.