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);
}
To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method. The DataTable then creates the DataRow object based on the structure of the table, as defined by the DataColumnCollection.
You create DataColumn objects within a table by using the DataColumn constructor, or by calling the Add method of the Columns property of the table, which is a DataColumnCollection. The Add method accepts optional ColumnName, DataType, and Expression arguments and creates a new DataColumn as a member of the collection.
To add or insert observation/row to an existing Data Frame in R, we use rbind() function. We can add single or multiple observations/rows to a Data Frame in R using rbind() function.
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With