我想在 C# 循环中将数据添加到数据表,但我不能。
我使用这段代码,但它运行 1 次而不是更多。什么时候i=2
它不起作用。
请帮忙。
DataTable dt = new DataTable();
dt.Columns.Add("ProductId");
dt.Columns.Add("ProductTotalPrice");
DataRow dr = dt.NewRow();
for (int i = 0; i < 10; i++)
{
dr["ProductId"] = i.ToString();
dr["ProductTotalPrice"] = (i*1000).ToString();
dt.Rows.Add(dr);
}
那是因为你只创建了一个DataRow
外部循环,因此您实际上是用新值覆盖了该行中的旧值。您的行创建应该在循环内部,因此每次迭代都会有新行,例如
DataTable dt = new DataTable();
dt.Columns.Add("ProductId");
dt.Columns.Add("ProductTotalPrice");
DataRow dr = null;
for (int i = 0; i < 10; i++)
{
dr = dt.NewRow(); // have new row on each iteration
dr["ProductId"] = i.ToString();
dr["ProductTotalPrice"] = (i*1000).ToString();
dt.Rows.Add(dr);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)