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


80

如何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
}

Answers:


124

只需继续处理您的代码-您就走在正确的轨道上:

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

dt.AcceptChanges()添加新的列和值后,您需要致电吗?
Michael Kniskern

2
@Michael:不,不是。现在,您的数据集已准备好这些新值。如果要保存,则需要某种方法将其写回(通过SqlDataAdapter或其他方法)。AcceptChanges()不会做任何事情(除了将那些更改标记为“ accepted”(接受)->在下次保存数据时不会检测到这些更改来保存!)
marc_s 2010年

12

应该不是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 
} 

7

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

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

2
@Akxaya,您介意该解决方案的工作原理吗?
MikaelDúiBolinder

DataTable dt = sql.ExecuteDataTable(“ sp_MyProc”); // dt.Columns.Add(“ MyRow”,typeof(System.Int32)); dt.Columns [“ MyRow”]。Expression =“'0'”;
Akxaya

6

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

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;
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.