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

C#DatatableDatarow

C# Problem Overview


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
}

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

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 
} 

Solution 3 - C#

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

dt.Columns.Add("MyRow", type(System.Int32),0);

Solution 4 - C#

Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";

Solution 5 - C#

Try this

> 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;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichael KniskernView Question on Stackoverflow
Solution 1 - C#marc_sView Answer on Stackoverflow
Solution 2 - C#Imir HoxhaView Answer on Stackoverflow
Solution 3 - C#NishanthaView Answer on Stackoverflow
Solution 4 - C#AkxayaView Answer on Stackoverflow
Solution 5 - C#Himanshu ShuklaView Answer on Stackoverflow