使用 CollectionView 过滤 DataTable 时为什么会出错? [英] Why errors when filters DataTable with CollectionView?
问题描述
如题.
所以我成功地将 DataTable
放入我的 CollectionView
中:
So I was successfully to put DataTable
into my CollectionView
with using:
ICollectionView _collectionView { get; set; }
public ICollectionView collectionView {......}
DataTable myDataTable= new DataTable();
myConnection.Open();
dbAdpater.Fill(myDataTable);
myConnection.Close();
var collectionList= (newLeadTable as IListSource).GetList();
this.collectionView = CollectionViewSource.GetDefaultView(collectionList);
我知道列表中的每个对象都是 DataRowView
并且当我通过迭代数据进行测试时,我可以看到存储正确.
I know each of the object in the list is DataRowView
and as I tested with iterating the data and I can see is stored properly.
当我执行代码时,DataGrid
显示正确.
The DataGrid
was display properly when I execute the code.
但是一旦我添加了过滤器:
But once I added the Filter:
this.collectionView.Filter = new Predicate<object>(
(obj) =>
{
return false; //Just for testing propose
}
);
当我执行代码时出现错误:
When I execute the code is giving me error:
无法创建程序集TestWPF"中定义的Window1"实例,版本=1.0.0.0,文化=中性,PublicKeyToken=null'.异常有被调用的目标抛出.标记文件中的错误'TestWPF;component/Window1.xaml' 第 1 行位置 9.
Cannot create instance of 'Window1' defined in assembly 'TestWPF, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Exception has been thrown by the target of an invocation. Error in markup file 'TestWPF;component/Window1.xaml' Line 1 Position 9.
和输出:
System.NotSupportedException"类型的第一次机会异常发生在 PresentationFramework.dll 中
A first chance exception of type 'System.NotSupportedException' occurred in PresentationFramework.dll
我也尝试将 DataTable
存储转换为用于过滤的 custom object
列表,但工作正常.
I also tried to stores converts the DataTable
into a list of custom object
for filtering, but is working fine.
所以我想知道在使用 DataTable
过滤时我做错了什么?
So I wonder what did I done wrong when filtering with DataTable
?
推荐答案
参见 http://msdn.microsoft.com/en-us/library/ms752347.aspx#binding_to_collections
为了提高性能,ADO.NET DataTable 或 DataView 对象的集合视图将排序和过滤委托给 DataView.
To improve performance, collection views for ADO.NET DataTable or DataView objects delegate sorting and filtering to the DataView.
BindingListCollectionView
不支持过滤.相反,您必须使用 CustomFilter 属性,它采用过滤器字符串并将其用作基础 DataView.RowFilter
属性的值.字符串值是用于在 SELECT 查询中构造 WHERE 子句的 SQL.
The BindingListCollectionView
does not support filtering. Instead, you have to use the CustomFilter property which takes a filter string and uses it as the value for the underlying DataView.RowFilter
property. The string value is SQL that you would use to construct the WHERE clause in a SELECT query.
this.collectionView.CustomFilter = "Price > 20";
如果你想使用多个条件,那么你必须用AND或OR将它们串在一起(就像SQL一样).
If you want to use multiple conditions, then you have to string them together with AND or OR (just like SQL).
这篇关于使用 CollectionView 过滤 DataTable 时为什么会出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!