C# 如何向已包含数据的数据表添加新列和数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2312966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:19:03  来源:igfitidea点击:

How can I add a new column and data to a datatable that already contains data?

c#datatabledatarow

提问by Michael Kniskern

How do I add a new DataColumnto a DataTableobject that already contains data?

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

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
}

采纳答案by marc_s

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

回答by Imir Hoxha

Should it not be foreachinstead of for!?

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

回答by Nishantha

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

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

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

回答by Akxaya

Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)

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

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

回答by Himanshu Shukla

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;