Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a new column and data to a datatable that already contains data?

How do I add a new DataColumn to a DataTable object that already contains data?

PseudoCode

//call SQL helper class to get initial data  DataTable dt = sql.ExecuteDataTable("sp_MyProc");  dt.Columns.Add("NewColumn", type(System.Int32));  foreach(DataRow row in dr.Rows) {     //need to set value to NewColumn column } 
like image 350
Michael Kniskern Avatar asked Feb 22 '10 18:02

Michael Kniskern


People also ask

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 you add data to a DataTable?

After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method.


2 Answers

Just keep going with your code - you're on the right track:

//call SQL helper class to get initial data  DataTable dt = sql.ExecuteDataTable("sp_MyProc");  dt.Columns.Add("NewColumn", typeof(System.Int32));  foreach(DataRow row in dt.Rows) {     //need to set value to NewColumn column     row["NewColumn"] = 0;   // or set it to some other value }  // possibly save your Dataset here, after setting all the new values 
like image 52
marc_s Avatar answered Oct 21 '22 16:10

marc_s


Should it not be foreach instead of for!?

//call SQL helper class to get initial data   DataTable dt = sql.ExecuteDataTable("sp_MyProc");   dt.Columns.Add("MyRow", **typeof**(System.Int32));   foreach(DataRow dr in dt.Rows)  {      //need to set value to MyRow column      dr["MyRow"] = 0;   // or set it to some other value  }  
like image 42
Imir Hoxha Avatar answered Oct 21 '22 15:10

Imir Hoxha