85

如何DataColumnDataTable已包含数据的对象添加新对象?

伪代码

//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
}
4

5 回答 5

142

继续使用您的代码 - 您走在正确的轨道上:

//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
于 2010-02-22T18:25:36.977 回答
13

不应该foreach代替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 
} 
于 2012-01-06T20:54:40.587 回答
8

这是减少 For/ForEach 循环的替代解决方案,这将减少循环时间并快速更新:)

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";
于 2015-03-02T22:16:48.133 回答
7

只有你想设置默认值参数。这调用了第三个重载方法。

dt.Columns.Add("MyRow", type(System.Int32),0);
于 2015-02-18T10:51:46.857 回答
2

尝试这个

> 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;
于 2015-07-14T18:03:15.857 回答