根据子行数过滤BindingSource

时间:2013-08-07 16:11:08

标签: c# .net data-binding filter ado.net

我正在开发我的第一个小型数据库应用程序,我在其中使用了类型DataSet和数据绑定:

enter image description here

我有customersBindingSource将客户列表绑定到左侧的ListBox,并allowedclientsBindingSource将允许的客户列表(所选客户的列表)绑定到{ {1}}在右边。

现在我想应用一个过滤器,以便只在右侧显示禁用的客户端。我可以通过设置

来做到这一点
DataGridView

这很好用。现在并非所有客户都有残疾客户。我想只显示左边那些实际上已禁用客户的客户。所以我正在寻找这样的东西:

allowedclientsBindingSource.Filter = "Enabled = 'false'";

当然,此customersBindingSource.Filter = "numberOfAllowedClients > 0"; 必须引用允许客户的过滤列表。

实现此目的的正确过滤器表达式是什么?

修改

如果可能的话,我想继续使用数据绑定而不是手动填充numberOfAllowedClients

我发现我可以根据子行数过滤客户列表,如下所示:

ListBox

但它使用未经过滤的客户列表。我也尝试过:

customersBindingSource.Filter = "Count(Child.AllowedClientID) > 0";

但这不起作用,因为customersBindingSource.Filter = "Count(Child.Enabled = 'false') > 0"; 聚合中不允许使用任何表达式。我还尝试在数据表的Count上设置RowFilter属性,而不是在绑定源上。但那也不起作用。

如果不手动操作,真的没有干净而简单的解决方案吗?

1 个答案:

答案 0 :(得分:1)

您可以使用LINQ创建临时数据表以用作数据源。

构建客户表:

DataTable Customer = new DataTable();
Customer.Columns.Add("CustomerID");
Customer.Columns.Add("Name");

DataRow Stefan = Customer.NewRow();
Stefan["CustomerID"] = 1;
Stefan["Name"] = "Stefan";
Customer.Rows.Add(Stefan);

DataRow Robert = Customer.NewRow();
Robert["CustomerID"] = 2;
Robert["Name"] = "Robert";
Customer.Rows.Add(Robert);

DataRow William = Customer.NewRow();
William["CustomerID"] = 3;
William["Name"] = "William";
Customer.Rows.Add(William);

构建客户端表:

DataTable Client = new DataTable();
Client.Columns.Add("ClientID");
Client.Columns.Add("CustomerID");
Client.Columns.Add("Enabled");

DataRow Client1 = Client.NewRow();
Client1["ClientID"] = 1;
Client1["CustomerID"] = 1;
Client1["Enabled"] = true;
Client.Rows.Add(Client1);

DataRow Client2 = Client.NewRow();
Client2["ClientID"] = 2;
Client2["CustomerID"] = 2;
Client2["Enabled"] = true;
Client.Rows.Add(Client2);

DataRow Client3 = Client.NewRow();
Client3["ClientID"] = 3;
Client3["CustomerID"] = 2;
Client3["Enabled"] = false;
Client.Rows.Add(Client3);

DataRow Client4 = Client.NewRow();
Client4["ClientID"] = 4;
Client4["CustomerID"] = 3;
Client4["Enabled"] = false;
Client.Rows.Add(Client4);

过滤客户端表for enabled = false:

BindingSource ClientBS = new BindingSource();
ClientBS.DataSource = Client;
ClientBS.Filter = "Enabled = false";

使用LINQ连接两个表并仅返回具有已禁用客户端的客户行:

var CustomersWithDisabledClients = from client in Client.AsEnumerable()
                                   from customer in Customer.AsEnumerable()
                                   where Convert.ToInt32(customer["CustomerID"]) == Convert.ToInt32(client["CustomerID"]) &&
                                   Convert.ToBoolean(client["Enabled"]) == false
                                   select new { CustomerID = customer["CustomerID"], Name = customer["Name"] };

克隆客户表并添加具有禁用客户端的客户行以与绑定源一起使用:

DataTable filteredCustomer = Customer.Clone();
CustomersWithDisabledClients.ToList().ForEach(r => filteredCustomer.Rows.Add(r));