问题描述
是否可以在Windows Forms应用程序中过滤列表框的内容?
Is it possible to filter the contents of a Listbox in a Windows Forms application?
我的ListBox的数据源是一个BindingSource,在其中包含一堆DTO:
The DataSource of my ListBox is a BindingSource containing a bunch of DTOs in an:
IList<DisplayDTO>
我要过滤ListBox的DisplayMember中指定的DTO属性.
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.
推荐答案
这应该有效:
private void textBox_TextChanged(object sender, EventArgs e)
{
bindingSource.Filter = string.Format("[{0}] LIKE '%{1}%'",
listBox.DisplayMember,
textBox.Text.Replace("'", "''"));
}
仅当基础数据源(bindingSource.DataSource
)实现IBindingListView
时,此方法才有效.在FCL中,只有DataView
类实现此接口.
this works only if the underlying data source (bindingSource.DataSource
) implements IBindingListView
. In the FCL, only the DataView
class implements this interface.
您可以通过从BindingList<T>
继承来创建自己的实现.这是一篇文章解释了如何添加过滤器功能.您还可以在Google上找到SortableBindingList
的各种实现.
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.
这篇关于在Windows窗体应用程序中过滤列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!