繁体   English   中英

获取typeof的DataGrid数据并进行强制转换

[英]Get typeof DataGrid data and cast as it

我在获取gridview数据并将其收敛到DataTable遇到问题。 有点像我的应用程序中的某些数据网格一样,它可以将ItemsSourceDataView ,但是另一个在应用程序中定义了ItemsSource

例如:

DataGrid1-ItemsSource = DataView(直接从数据库访问)DataGrid2-ItemsSource =产品的ObservableCollection DataGrid3-ItemsSource =类别的ObservaleCollection

我得到的错误:

无法将类型为System.Collections.ObjectModel.ObservableCollection`1[myApp.Product]对象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();
  }

所以实际上我想将collection作为对象并将ItemsSourceDataTable

可能吗

是的,可能...您的错误说

无法将类型为'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的显式(C#参考)页面中找到更多信息。 您可以从MSDN的DataView.Table属性页中找到如何填充DataTable

更新>>>

不是一种方法。 它是演员。 用于将一种类型转换为另一种类型。 在以下示例中,类似于(int)

int intValue = (int)doubleValue;

您询问了如何将ObservableCollection转换为DataView 我的答案向您展示了如何做到这一点:

DataView dataView = (DataView)yourCustomObservableCollection;

或从您的示例中:

dt = ((DataView)dg.ItemsSource).ToTable();

...假设存在此自定义MyObservableCollection的实例,该实例设置为dg.ItemsSource

你说

DataGrid2-ItemsSource =产品的ObservableCollection DataGrid3-ItemsSource =类别的ObservaleCollection

  1. 因此,首先,像我向您展示的那样创建一个新类。

  2. 接下来,用新的MyObservableCollection实例替换当前的ObservableCollection实例。

而已。 我不知道该怎么解释。 如果您真的不明白这一点,那么您就没地方问这些问题了。 我建议您去MSDN学习有关铸造的所有知识,然后回来理解这一点。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM