如何向已经包含数据的数据表中添加新的列和数据?

如何向已经包含数据的 DataTable对象添加新的 DataColumn

伪代码

//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
}
333475 次浏览

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

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
}

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

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

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

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;