将新列和数据添加到已包含数据的数据表中 - c#

Mic*_*ern 69 c# datatable datarow

如何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
}
Run Code Online (Sandbox Code Playgroud)

mar*_*c_s 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
Run Code Online (Sandbox Code Playgroud)

  • @Michael:不,不是真的.现在,您的数据集已准备好这些新值.如果要保存它,则需要使用某种方法将其写回(通过SqlDataAdapter或其他方法).AcceptChanges()不会做任何事情(除了将这些更改标记为"已接受" - >下次保存数据时不会检测到它们保存!) (2认同)

Imi*_*xha 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 
} 
Run Code Online (Sandbox Code Playgroud)


Nis*_*tha 7

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

dt.Columns.Add("MyRow", type(System.Int32),0);
Run Code Online (Sandbox Code Playgroud)


小智 5

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

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";
Run Code Online (Sandbox Code Playgroud)

  • @Akxaya,您介意详细说明该解决方案的工作原理吗? (3认同)