Add a new column and data to a datatable that already contains data - C #

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

pseudo code

 //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 } 
+49
c # datatable datarow
Feb 22 2018-10-22
source share
5 answers

Just continue with the 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 
+78
Feb 22 '10 at 18:25
source share

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 } 
+10
Jan 06 2018-12-12T00:
source share

Here is an alternative solution to shorten the For / ForEach cycle, it will reduce cycle time and update quickly.

  dt.Columns.Add("MyRow", typeof(System.Int32)); dt.Columns["MyRow"].Expression = "'0'"; 
+2
Mar 02 '15 at 10:16
source share

Try

 > dt.columns.Add("ColumnName", typeof(Give the type you want)); > dt.Rows[give the row no like or or any no]["Column name in which you want to add data"] = Value; 
+2
Jul 14 '15 at 18:03
source share

Only you want to set the default value parameter. This calling third overload method.

 dt.Columns.Add("MyRow", type(System.Int32),0); 
+1
Feb 18 '15 at 10:51
source share



All Articles