问题
I want to add data to datatable within a loop in c# but I cannot.
I use this code but it runs 1 time not more. When i=2
it dose not work.
Please help.
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);
}
回答1:
That's cause you are creating only one DataRow
outside loop and so you are actually over writing the old values in that row with new one's. Your row creation should be inside loop and thus you will have new row per iteration like
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:
for (int i = 0; i < 10; i++)
{
dr = dt.NewRow();
dr["ProductId"] = i.ToString();
dr["ProductTotalPrice"] = (i*1000).ToString();
dt.Rows.Add(dr);
}
Should work.
Each time you need to add different dataRow. You're trying to add the same.
回答3:
Yet another simple way:
for (int i = 0; i < 10; i++)
{
dt.Rows.Add(i, i * 1000);
}
来源:https://stackoverflow.com/questions/43946260/how-to-add-data-to-datatable