【问题标题】:Add Dataset to Another Dataset Like a DataRow in C#将数据集添加到另一个数据集,如 C# 中的 DataRow
【发布时间】:2012-12-31 01:19:03
【问题描述】:
            sqlHelper = new SqlHelper();
            sqlHelper.OpenConnection();
            int i;
            String sqlSt = string.Empty;
            for (i = 0; i < tag.Count; i++)
            {
               sqlSt = "Select TagID from TagsList where TagName= '" + tag[i] + "'";
               ds = sqlHelper.ExecuteDataSet(sqlSt, CommandType.Text);

               if (ds != null)
               {
                   if (ds.Tables[0].Rows.Count > 0)
                   {
                       //dt = ds1.Tables[0];
                       ds.Tables[0].Rows.Add(ds);
                   }
               }
             }
             return ds;

我想将一个数据集添加到另一个数据集,最后会返回累积的数据集。

我收到一个错误 - Unable to cast object of type 'System.Data.DataSet' to type 'System.IConvertible'.Couldn't store &lt;System.Data.DataSet&gt;

编辑: 我想要的是我得到一个包含特定 int 值的数据集,我的 for 循环运行的每种类型我想将所有这些记录添加到数据集中,然后返回我的数据集

【问题讨论】:

  • 您必须逐行到DataTable。而不是 Add() 使用 ImportRow()

标签: c# asp.net datatable dataset


【解决方案1】:

技术上我们不能将一个数据集添加到其他数据集,因为 ASP.NET 中的数据集通常是只读的。

所以,首先我们必须创建第二个数据集的对象引用。

步骤:

bool IsFirstTime  = true;(Create OutSide Loop)

内循环:

if (IsFirstTime)

{

// dsLoopData Contains Records

dsTotalRecords = dsLoopData.Clone();

IsFirstTime = false;

}

1.一次插入(用于批量复制)

dsTotalRecords.Tables[0].Merge(dsLoopData.Tables[0]);

2.逐行插入

for (int i = 0; i < dsLoopData.Tables[0].Rows.Count; i++)

{

dsTotalRecords.Tables[0].ImportRow(dsLoopData.Tables[0].Rows[i]);

}

【讨论】:

    【解决方案2】:

    我想知道这是否是一个错字,因为您将相同的 DataSet 添加到其第一个表的行集合中:

    ds.Tables[0].Rows.Add(ds);

    如果我理解正确,您有一个数据集ds1,并且您想将其表添加到ds。为此,您需要分两步逐表移动:克隆表并导入其行

    例如,这会复制第一个表(索引 0):

    //clone first table
    DataTable dt = ds1.Tables[0].Clone();
    //add rows
    foreach (DataRow dr in ds1.Tables[0].Rows)
    {
        dt.ImportRow(dr);
    }
    //add table to DataSet
    ds.Tables.Add(dt); 
    

    已编辑: 我也会调查DataTableExtensionsCopyToDataTable。它相信你也可以这样做(未经测试):

    //copy first table
    DataTable dt = ds1.Tables[0].AsEnumerable().CopyToDataTable();    
    //add table to DataSet
    ds.Tables.Add(dt); 
    

    【讨论】:

    • 如果我理解正确,您将检查一个值并根据该值添加记录?最后返回数据集?
    猜你喜欢
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    • 1970-01-01
    相关资源
    最近更新 更多