如何将datarow转换为datatable

时间:2009-11-08 17:09:04

标签: asp.net

DataRow [] row = table.Select(“Weight = '57'”); //有1条记录       DataTable dt = new DataTable();

     foreach (DataRow dr in row)
                {
                    dt.ImportRow(dr);
                }
                dt.AcceptChanges();

我的行有1条记录。当我尝试将datarow []行转换为datatable时 它运行正常。当我检查 dt 时,它不包含任何记录 。它的问题是什么

谢谢

6 个答案:

答案 0 :(得分:6)

DataTable dt = new DataTable();

DataRow[] dr = dt.Select("Your string");

DataTable dt1 = dr.copyToDataTable();

答案 1 :(得分:2)

您应该将行复制到新行,然后将其添加到新表中。 你不能从一张桌子上取一排,把它放在另一张桌子上。

来自其他网站的代码示例:

DataTable dtDest = new DataTable();
dtDest = dsActivity.Tables[0].Clone();
foreach(DataRow dr in dsSrc.Tables[0].Rows)
{
 DataRow newRow = dtDest .NewRow();
 newRow.ItemArray = dr.ItemArray;
 dtDest.Rows.Add(newRow);
}

克隆使dtDest与源类型(列)相同。

另一种方法是创建一个新行,添加正确的列,并按值复制值。

答案 2 :(得分:2)

DataRow[] rows = table.Select("Weight='57'");
DataTable dt = new DataTable();

foreach (DataRow item in rows)
{
    // add values into the datatable
    dt.Rows.Add(item.ItemArray);
}

答案 3 :(得分:1)

尝试以下方法:

dt.Rows.Add(dr)

答案 4 :(得分:1)

DataTable DT = DTMain.Clone();
// suppose DT is the table where we need to put datarows and DTMain is a table
// having the stucture of the datatbale, means you must have some structure for
// datatable.

//supposes you have a collection of datarows as

foreach(DataRow dr in DatarRowColl)
{
    DT.ImportRow(dr);
}

DT.AcceptChanges();

// here you get the datarows in a datatable.

快乐编程。

答案 5 :(得分:1)

dim dt as new DataTable
dim row as new DataRow
dim params(10) as string
''''' imagine we have row and we fill it
''''' you should create your dataTable as you want
dt.Columns.Add("column1")
dt.Columns.Add("column2")
.
.
.
For Each r As DataRow In row
    params = {dr.Item("column1"), dr.Item("column2")}
    dt.Rows.Add(params)
Next
dt.AcceptChanges()