【问题标题】:Cannot implicitly convert type 'System.Data.DataTable' to DataSets.General.StudentDataTable'无法将类型“System.Data.DataTable”隐式转换为 DataSets.General.StudentDataTable'
【发布时间】:2013-01-24 05:45:51
【问题描述】:

我有一个包含一些数据表的数据集,现在我想从 db 中获取一个数据表并将其添加到我正在使用的数据集中的现有数据表中

  return (DataSets.General.StudentDataTable) ds.Tables["DSDummy"];

但它给了我以下错误

无法将类型“System.Data.DataTable”隐式转换为 DataSets.General.StudentDataTable'。存在显式转换

有人可以告诉我如何投射这个对象吗?任何帮助将不胜感激

谢谢

【问题讨论】:

  • ds.Tables["DSDummy"]实际上是DataSets.General.StudentDataTable类型的强类型DataTable吗?
  • 我不希望那行代码产生那个编译错误。你方法的返回类型是什么?
  • 我的方法的返回类型是“DataSets.General.StudentDataTable”,DSDummy是一个强类型数据表。它不会给出任何编译时错误,但会给出一个异常,例如“无法转换等”
  • ds.Tables["DSDummy"] 是强类型 DataSets.General.StudentDataTable?不只是碰巧有相同的类型定义吗?从 db 中获取数据表是什么意思?

标签: c# .net datatable dataset


【解决方案1】:

如果ds 是强类型数据集,我希望它具有DSDummy 表的显式属性,例如ds.DSDummy,而不是通过绕过强类型的Tables 集合。

但是,即使是这样,显式转换应该也有效。您是否有可能不止一次定义了 DataSets.General.StudentDataTable - 一次是手动定义的,一次是从 DataSet Generator 自动定义的 - 并且存在冲突?

【讨论】:

    【解决方案2】:

    如果您尝试将一个DataTable 加载到另一个,您可以使用DataTable.Merge 方法:

    DataSets.General.StudentDataTable.Merge(ds.Tables["DSDummy"]);
    

    【讨论】:

      【解决方案3】:

      查看MSDN documentation

      以下代码取自上述链接。

      DataSet customerOrders = new DataSet("CustomerOrders");
      
      DataTable ordersTable = customerOrders.Tables.Add("Orders");
      
      DataColumn pkOrderID =
      ordersTable.Columns.Add("OrderID", typeof(Int32));
      ordersTable.Columns.Add("OrderQuantity", typeof(Int32));
      ordersTable.Columns.Add("CompanyName", typeof(string));
      
      ordersTable.PrimaryKey = new DataColumn[] { pkOrderID };
      

      【讨论】:

        【解决方案4】:

        试试下面...可能对你有帮助...

        如果要返回数据集并分配给数据集,请按照以下方法..

        DataSet ds = new DataSet();
        ds = GetData();
        
        public dataset Sample GetData()
        {
        ......
        .......
        
        return ds
        }
        

        如果您想返回 Datatable 并将其分配给 Dataset,请按照以下方法操作。

        DataSet ds = new DataSet();
        ds.Tables.Add(GetData());
        
        
        public datatable Sample GetData()
        {
        ......
        .......
        
        return ds.Tables["DSDummy"];
        }
        

        【讨论】:

        • @Down 投票人:你能告诉我downVoted 的原因...吗?
        • 好吧,您不仅没有回答问题,而且您的代码示例大多是填充物,基本上包含 OP 中的代码。
        猜你喜欢
        • 1970-01-01
        • 2016-09-20
        • 1970-01-01
        • 2021-08-05
        • 2018-02-14
        • 1970-01-01
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多