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

Michael Kniskern picture Michael Kniskern · Feb 22, 2010 · Viewed 274.2k times · Source

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
}

Answer

marc_s picture marc_s · Feb 22, 2010

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