我在BindingSource
中过滤数据时遇到问题。我将数据列在DataGridView
。
class client
{
public int id { get; set; }
public String name { get; set; }
public client(String name)
{
this.name = name;
this.id = 0;
}
}
BindingSource clients = new BindingSource();
clients.Add(new client("Test1"));
clients.Add(new client("Test2"));
dataGridView_clients.AutoGenerateColumns = false;
dataGridView_clients.ColumnCount = 2;
dataGridView_clients.Columns[0].Name = "id";
dataGridView_clients.Columns[0].DataPropertyName = "id";
dataGridView_clients.Columns[1].Name = "name";
dataGridView_clients.Columns[1].DataPropertyName = "name";
dataGridView_clients.DataSource = clients_source;
clients.Filter = string.Format("Name = 'Test1'");
dataGridView_clients.Refresh();
我做错了什么?过滤器不起作用,它显示在最后两个客户端中。
答案 0 :(得分:0)
问题是因为BindingSource
默认情况下不支持过滤。如果您调试代码,则会看到属性SupportsFiltering
为false
。
要解决此问题,您需要实施IBindingListView
,然后绑定到BindingSource
,因为您可以实现过滤器的工作方式。
您可以按照本文中介绍的步骤实施IBindingListView
。
https://blogs.msdn.microsoft.com/winformsue/2007/12/07/implementing-the-ibindinglistview-for-filtering/
答案 1 :(得分:0)
您可以检查绑定源是否像这样处理过滤
Game game = new Game();
game.InScreen();
在您的情况下,不支持过滤。 要解决此问题,您可以在其上实现IBindingListView接口。 请参阅:Implementing the IBindingListView for filtering
答案 2 :(得分:0)
您可以在数据绑定之前过滤列表:
List<client> clients = new List<client> { new client("Test1"), new client("Test2") };
List<client> filtered = clients.FindAll(c => c.name == "Test2");
dataGridView1.DataSource = filtered;