如何将数据添加到数据表

时间:2017-05-12 20:49:05

标签: c# datatable

我想在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);
}

3 个答案:

答案 0 :(得分:3)

for (int i = 0; i < 10; i++)
{
    dr = dt.NewRow();
    dr["ProductId"] = i.ToString();
    dr["ProductTotalPrice"] = (i*1000).ToString();
    dt.Rows.Add(dr);
}

应该工作。

每次需要添加不同的dataRow。您正在尝试添加相同内容。

答案 1 :(得分:3)

这是因为您只创建了一个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);
}

答案 2 :(得分:0)

另一种简单的方法:

for (int i = 0; i < 10; i++)
{
    dt.Rows.Add(i, i * 1000);
}