Filtering Listboxes in a Windows Forms application

2019-09-02 06:50发布

问题:

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:

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.