Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add data to datatable

Tags:

c#

datatable

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);
}
like image 384
Hossein Tavakoli Avatar asked May 12 '17 20:05

Hossein Tavakoli


People also ask

How add data row to DataTable?

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.

How do I add a column to a DataTable?

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.

How do I add data to a table in R?

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.


2 Answers

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);
}
like image 186
Rahul Avatar answered Sep 30 '22 19:09

Rahul


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.

like image 25
Prajwal Avatar answered Sep 30 '22 20:09

Prajwal