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 }
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.
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.
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
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 }
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