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

问题描述 投票:70回答:5

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

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
}
c# datatable datarow
5个回答
111
投票

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

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

11
投票

应该不是foreach而不是!!

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

5
投票

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

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";

4
投票

仅您要设置默认值参数。此调用第三个重载方法。

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

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;
© www.soinside.com 2019 - 2024. All rights reserved.