我遇到了获取gridview数据并将其转换为DataTable
的问题。非常像我的应用程序中的一些数据网格有ItemsSource
我可以强制转换为DataView
,但另一个在应用程序中定义了ItemsSource
。
例如:
DataGrid1 - ItemsSource = DataView(直接来自数据库) DataGrid2 - ItemsSource =产品的ObservableCollection DataGrid3 - ItemsSource =类别的ObservaleCollection
我得到的错误:
无法投射类型的对象
System.Collections.ObjectModel.ObservableCollection`1[myApp.Product]
输入System.Data.DataView
。
我希望达到这样的目标:
DataTable dt = null;
try
{
dt = ((DataView)dg.ItemsSource).ToTable();
}
catch
{
Type t = dg.ItemsSource.GetType();
dt = ((t)dg.ItemsSource).ToTable();
}
所以实际上我想将集合作为对象并将ItemsSource
强制转换为DataTable
。
甚至可能吗?
答案 0 :(得分:0)
是的,有可能......你的错误说
无法将类型为'System.Collections.ObjectModel.ObservableCollection`1 [myApp.Product]'的对象强制转换为'System.Data.DataView'
这意味着这些类之间没有直接的转换关系。为了提供这一点,您必须扩展ObservableCollection<T>
类并覆盖explicit
强制转换运算符:
public class MyObservableCollection : ObservableCollection<YourDataType>
{
public static explicit operator DataView(MyObservableCollection collection)
{
DataTable table = new DataTable();
foreach (YourDataType item in collection)
{
// fill your DataTable however you want to here
}
return new DataView(table);
}
}
您可以在MSDN的explicit (C# Reference)页面上找到更多信息。您可以在MSDN的DataView.Table Property页面上了解如何填充DataTable
。
更新&gt;&gt;&gt;
这是不是方法。它是一个演员。它用于将一种类型铸造成另一种类型。与以下示例中的(int)
类似:
int intValue = (int)doubleValue;
您问过如何将ObservableCollection
投射到DataView
。我的回答告诉你如何做到这一点:
DataView dataView = (DataView)yourCustomObservableCollection;
或者来自您的示例:
dt = ((DataView)dg.ItemsSource).ToTable();
...假设此自定义MyObservableCollection
的实例设置为dg.ItemsSource
。
你说
DataGrid2 - ItemsSource =产品DataGrid3的ObservableCollection - ItemsSource =类别的ObservaleCollection
首先,创建一个新的类,就像我给你看的那样......把它称之为你喜欢的。
接下来,将您当前的ObservableCollection
个实例替换为新的MyObservableCollection
个实例。
就是这样。我不知道如何解释它。如果您真的不理解这一点,那么您就无法提出这些问题。我建议你去MSDN学习关于铸造的所有内容,然后再回过头来理解这一点。