Add new column and data to datatable that already

2019-01-22 00:41发布

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
}

5条回答
劫难
2楼-- · 2019-01-22 01:19

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

dt.Columns.Add("MyRow", type(System.Int32),0);
查看更多
再贱就再见
3楼-- · 2019-01-22 01:22

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 
} 
查看更多
孤傲高冷的网名
4楼-- · 2019-01-22 01:32

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'";
查看更多
小情绪 Triste *
5楼-- · 2019-01-22 01:43

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
查看更多
冷血范
6楼-- · 2019-01-22 01:46

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;
查看更多
登录 后发表回答