Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a new row into DataTable

Tags:

c#

datatable

I have a datatable filled with staff data like..

Staff 1 - Day 1 - Total Staff 1 - Day 2 - Total Staff 1 - Day 3 - Total Staff 2 - Day 1 - Total Staff 2 - Day 2 - Total Staff 2 - Day 3 - Total Staff 2 - Day 4 - Total 

I want to modify so that the result would be sth like..

Staff 1 - Day 1 - Total Staff 1 - Day 2 - Total Staff 1 - Day 3 - Total Total   -       - Total Value Staff 2 - Day 1 - Total Staff 2 - Day 2 - Total Staff 2 - Day 3 - Total Staff 2 - Day 4 - Total Total   -       - Total Value 

to be concluded, I need to insert the total row at the end of each staff record.

So, my question is how to insert a row into a datatable? Tkz..

like image 844
william Avatar asked Jan 19 '11 04:01

william


People also ask

How do I add a row to a 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 row to a DataTable in R?

With command rbindlist from the data. table package, we can append dt_add_row and new_row row-wise. Object dt_add_row, shown in Table 2, shows the original data. table with the added row number 6.

How do I create a new DataRow?

To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition.


1 Answers

@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

//Creating dummy datatable for testing DataTable dt = new DataTable(); DataColumn dc = new DataColumn("col1", typeof(String)); dt.Columns.Add(dc);  dc = new DataColumn("col2", typeof(String)); dt.Columns.Add(dc);  dc = new DataColumn("col3", typeof(String)); dt.Columns.Add(dc);  dc = new DataColumn("col4", typeof(String)); dt.Columns.Add(dc);  DataRow dr = dt.NewRow();  dr[0] = "coldata1"; dr[1] = "coldata2"; dr[2] = "coldata3"; dr[3] = "coldata4";  dt.Rows.Add(dr);//this will add the row at the end of the datatable //OR int yourPosition = 0; dt.Rows.InsertAt(dr, yourPosition); 
like image 111
samar Avatar answered Oct 09 '22 22:10

samar