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

91

如何向已包含数据的DataTable对象中添加一个新的DataColumn

伪代码

//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
}
6个回答

153

继续编写你的代码,你正在正确的道路上:

//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() 不会做任何事情(除了将这些更改标记为“已接受” -> 下次保存数据时,它们不会被检测到以保存!) - marc_s

14

应该使用 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 
} 

10

只有在想要设置默认值参数时,才会调用第三个重载方法。

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

1
“type” 应该改为 “typeof” 吗? - Fritz W

9

这里有一个替代方案来减少 For/ForEach 循环,它可以缩短循环时间并快速更新 :)

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

3
@Akxaya,您能详细介绍一下该解决方案是如何运作的吗? - Mikael Dúi Bolinder
DataTable dt = sql.ExecuteDataTable("sp_MyProc"); // dt.Columns.Add("MyRow", typeof(System.Int32)); dt.Columns["MyRow"].Expression = "'0'"; 数据表 dt = sql.ExecuteDataTable("sp_MyProc"); // dt.Columns.Add("MyRow", typeof(System.Int32)); dt.Columns["MyRow"].Expression = "'0'"; - Akxaya
Expression 支持许多其他功能,如计算、聚合、比较、IIF、LIKE、ISNULL等。 - ourmandave

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;

1
在 net6.0 语言版本的 C# 10 中,设置默认值的解决方案是:
dt.Columns.Add("MyRow", type(System.Int32)).DefaultValue = 0;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接