How to add data to datatable
c#, datatable
Solution
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);
}
Problem
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); } ```