复制两个不同表的DataColumns [英] Copying DataColumns of two different tables

查看:77
本文介绍了复制两个不同表的DataColumns的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想将tb1中的"a"列和tb2中的"c"列复制到表tb3中. "a"列和"c"列的长度不同. tb1和tb2数据表位于数据集ds11中.

请提前帮助我.

Hi,

I wanna copy column "a" from tb1 and column "c" from tb2 to table tb3. length of column "a" and column "c" are different. tb1 and tb2 DataTables are in a DataSet ds11.

Please help me out thanks in advance.

推荐答案

类似这样的东西
Something like this
DataTable dt1 = new DataTable();
DataColumn column1 = new DataColumn("First Column");
dt1.Columns.Add(column1);
DataTable dt2 = new DataTable();
DataColumn column2 = new DataColumn("First Column");
dt2.Columns.Add(column2);

DataTable dt3 = new DataTable();
dt3.Columns.Add(dt1.Columns[0]);
dt3.Columns.Add(dt2.Columns[0]);


Shwetha,

不幸的是,没有实现用于克隆dataColumns的直接方法.但是对于您的挑战,想到了两种可能的解决方案.

1.创建该列之后,遍历所有行以将数据从源复制到目标.
2.执行一个datatable1.Copy()复制所有列和数据,并删除不需要的列.

我已经提供了解决方案1的样本,因为解决方案2可以很好地自我说明.首先创建一个方法,该方法允许您通过遍历该列中的数据行来复制数据列的内容.

Hi Shwetha,

Unfortunately there is no direct method implemented for cloning dataColumns. But for your challenge, two possible solutions pop to mind.

1. After creating the column, loop through all rows to copy the data from the source to the target.
2. Do a datatable1.Copy() to copy all columns+data and delete the ones you don''t need.

I''ve included a sample for solution 1, as solution 2 is pretty self explainatory. First create a method that allows you to copy content of datacolumns by iterating through the datarows in that column.

private void CopyColumns(DataTable source, DataTable dest, params string[] columns)
{
  foreach (DataRow sourcerow in source.Rows)
  {
     DataRow destRow = dest.NewRow();
     foreach(string colname in columns)
     {
        destRow[colname] = sourcerow[colname];
     }
     dest.Rows.Add(destRow);
  }
}



您可以使用以下命令调用此方法:(命名任何列)



You can call this method by using : ( naming any column )

CopyColumns(source, destiny, "Column1", "column2");



或者在您的特定示例中为:



Or in your particular example that would be :

CopyColumns(tb1, tb3, "a");
CopyColumns(tb2, tb3, "c");



不要忘记先在tb3中使用正确的属性创建列,否则该方法将失败.另一种选择是遍历表中的行:



Don''t forget to create the columns in tb3 with the right properties first, or the method will fail. An alternative would be looping through the rows in the tables :

private void CopyColumn(DataTable srcTable, DataTable dstTable, string srcColName, string dstColName)
{
    foreach (DataRow row in srcTable.Rows )
    {
        DataRow newRow = dstTable.NewRow();
        newRow[dstColName] = row[srcColName];
        dstTable.Rows.Add(newRow);
    }
}



重要提示:不要忘记在tb3中创建列,否则两种方法都会失败.

干杯,

里克



Important : Don''t forget to create the columns in tb3, or both methods will fail.

Cheers,

Rick


这篇关于复制两个不同表的DataColumns的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆