C# 如何在数据表中追加一行?
我有一个数据表,比如dt1(它在一个循环中不断地改变它的属性)。我有另一个数据表,比如dt2(最初为空)。现在我必须将dt1的行附加到dt2中。我尝试使用Merge(),但前面的dt2行正在消失。C# 如何在数据表中追加一行?,c#,asp.net,C#,Asp.net,我有一个数据表,比如dt1(它在一个循环中不断地改变它的属性)。我有另一个数据表,比如dt2(最初为空)。现在我必须将dt1的行附加到dt2中。我尝试使用Merge(),但前面的dt2行正在消失。 你知道怎么做吗?根据你的代码,我看到你使用的是dt2=dt1.Clone(); 这将擦除dt2中的所有内容,因此只将dt1的当前内容添加到dt2中 您不应该进行克隆,而应该将dt1的内容合并到dt2。这样做怎么样: DataRow[] rows = new DataRow[dt1.Rows.Cou
你知道怎么做吗?根据你的代码,我看到你使用的是dt2=dt1.Clone(); 这将擦除dt2中的所有内容,因此只将dt1的当前内容添加到dt2中 您不应该进行克隆,而应该将dt1的内容合并到dt2。这样做怎么样:
DataRow[] rows = new DataRow[dt1.Rows.Count];
dt1.Rows.CopyTo(rows, 0);
foreach (DataRow row in rows)
{
dt2.Rows.Add(row);
}
使用如下方法:
var table2 = new DataTable();
foreach(DataRow row in table1.Rows)
table2.ImportRow(row);
我假设你们的桌子有相同的结构
foreach (DataRow row in dt1.Rows)
dt2.Rows.Add(row.ItemArray);
每次循环运行时,您都会清除
dt2
表。试试这个:
DataTable dt1 = null; DataTable dt2 = null;
for (int i = 0; i < dt3.Rows.Count; i++)
{
// here "strSQL" is build which changes on the "i" value
dt1 = GetDataTable(strSQL); // this returns a table with single Row
if(dt2 == null)
{
dt2 = dt1.Clone();
}
dt2.Merge(dt1,true);
}
而不是
dt2.Merge(dt1,true);
João Angelo回答的另一个派生方法是提前初始化dt2,然后可以删除空检查
DataTable dt1 = null; DataTable dt2 = new DataTable();
for (int i = 0; i < dt3.Rows.Count; i++)
{
// here "strSQL" is build which changes on the "i" value
dt1 = GetDataTable(strSQL); // this returns a table with single Row
dt2.Merge(dt1,true);
}
DataTable dt1=null;DataTable dt2=新的DataTable();
对于(int i=0;i
对于firstcase,我遇到错误(对象引用未设置为对象的实例)。对于dt2.Merge(dt1,true),前面的行将在后续的合并函数中被删除。您是否可以在问题中粘贴一些代码,以便我们看到发生了什么?”因为我的回答应该正常。
DataTable dt1 = null; DataTable dt2 = new DataTable();
for (int i = 0; i < dt3.Rows.Count; i++)
{
// here "strSQL" is build which changes on the "i" value
dt1 = GetDataTable(strSQL); // this returns a table with single Row
dt2.Merge(dt1,true);
}