views:

374

answers:

1

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("MyRow", type(System.Int32));

for(DataRow dr in dr.Rows)
{
    //need to set value to MyRow column
}
+1  A: 

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("MyRow", type(System.Int32));

for(DataRow dr in dt.Rows)
{
    //need to set value to MyRow column
    dr["MyRow"] = 0;   // or set it to some other value
}

// possibly save your Dataset here, after setting all the new values
marc_s
Did you need to call `dt.AcceptChanges()` after I add the new column and value?
Michael Kniskern
@Michael: no, not really. Your data set is now prepped with those new values. If you want to save it, you need to have some kind of method to write it back (through the SqlDataAdapter or some other means). AcceptChanges() won't do anything (except mark those changes as "accepted" -> they won't be detected for saving the next time you save your data!)
marc_s
Thanks for the information.
Michael Kniskern