Michael Kniskern
Michael Kniskern

Reputation: 25260

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

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
}

Upvotes: 95

Views: 377403

Answers (6)

Legit007
Legit007

Reputation: 193

In net6.0 Language Version C# 10 the solution for setting a default value is:

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

Upvotes: 1

marc_s
marc_s

Reputation: 754268

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

Upvotes: 159

Imir Hoxha
Imir Hoxha

Reputation: 1694

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 
} 

Upvotes: 14

Himanshu Shukla
Himanshu Shukla

Reputation: 145

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;

Upvotes: 2

Akxaya
Akxaya

Reputation: 844

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

Upvotes: 9

Nishantha
Nishantha

Reputation: 6685

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

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

Upvotes: 10

Related Questions