How to add data to datatable

一世执手 提交于 2021-01-18 12:37:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!