我想使用oldDT
方法将旧数据表(dt
)中的所有行复制到新数据表(ImportRow
)。但是新行与旧行没有相同的列。这是我的代码:
foreach (DataRow dr in oldDT.Rows)
{
MessageBox.Show(dr["tenant_no"].ToString()); //giving a correct result
dt.ImportRow(dr);
MessageBox.Show(dt.Rows[0]["tenant_no"].ToString()); //giving an error Column 'tenant_no' does not belong to table .
}
我尝试使用答案C# simple way to copy or clone a DataRow?,这是我的新代码:
foreach (DataRow dr in oldDT.Rows)
{
MessageBox.Show(dr["tenant_no"].ToString());
DataRow newDR = oldDT.NewRow();
newDR.ItemArray = dr.ItemArray.Clone() as object[];
dt.Rows.Add(newDR); //giving an error "This row already belongs to another table."
MessageBox.Show(dt.Rows[0]["tenant_no"].ToString());
}
任何人都可以帮助我?
答案 0 :(得分:1)
答案 1 :(得分:1)
试试这个......这样可行
DataTable dt= new DataTable();
dt= oldDT.Clone();
for (int i=0;i < oldDT.Rows.Count; i++)
{
dt.ImportRow(dataTable.Rows[i]);
}