views:

178

answers:

1

Is it possible to filter the contents of a Listbox in a Windows Forms application?

The DataSource of my ListBox is a BindingSource containing a bunch of DTOs in an:

IList<DisplayDTO>

I want to filter on the DTO property that is specified in the ListBox's DisplayMember.

The text to be filtered on is provided in a separate Text Box.

+1  A: 

This should work :

private void textBox_TextChanged(object sender, EventArgs e)
{
    bindingSource.Filter = string.Format("[{0}] LIKE '%{1}%'",
                                         listBox.DisplayMember,
                                         textBox.Text.Replace("'", "''"));
}

EDIT: this works only if the underlying data source (bindingSource.DataSource) implements IBindingListView. In the FCL, only the DataView class implements this interface.

You can create your own implementation by inheriting from BindingList<T>. Here's an article that explains how to add the filter functionality. You can also find various implementations of SortableBindingList on Google.

Thomas Levesque
I've tried what you've suggested, with a few variations, and still haven't been able to get it to work. I read that it could be something to do with the container that is used within the BindingSource.Changing it to a BindingList didn't help any.
Benny Hallett
Unfortunately the `BindingList<T>` implementation provided with the .NET framework doesn't support sorting and filtering... Here's a post that explains how to add the filter functionality : http://www.nablasoft.com/alkampfer/index.php/2008/11/22/extend-bindinglist-with-filter-functionality/.
Thomas Levesque
Ah, cheers mate :)
Benny Hallett