将列附加到具有动态绑定值的现有数据表 [英] Append a column to an existing Datatable with dynamically bound values
问题描述
我在 Vb 中有以下数据表
I have the following Datatable in Vb
Id Price
----- -------
1231 100
1232 150
1235 150
我想向名为 flag
的数据表添加第三列,其中包含 Id
I want to add a third column to that datatable called flag
, with values of the last digit of Id
如下:
Id Price Flag
----- ------ ----------
1231 100 1
1232 150 2
1235 150 5
如何使用动态绑定值将列附加到现有数据表?
How do I append a column to an existing Datatable, with dynamically bound values?
有没有一种方法可以在不使用 For 循环的情况下做到这一点?
Is there a way I can do this without using a For Loop?
任何帮助将不胜感激
推荐答案
首先需要添加一个DataColumn
:
table.Columns.Add("Flag", typeof(int));
现在您只需要相应地添加值:
Now you just need to add the values accordingly:
foreach(DataRow row in table.Rows)
{
int ID = row.Field<int>("ID");
string lastDigit = ID.ToString().Last().ToString();
row.SetField("Flag", int.Parse(lastDigit));
}
避免循环的唯一方法是首先用这些值填充它,例如,如果它是从数据库填充的.因此,即使 DataColumn.Expression
存在的方法(这里不是这种情况)会导致框架中的循环.
The only way to avoid a loop is to fill it with these values in the first place, for example if it's filled from database. So even if a DataColumn.Expression
approach existed(which is not the case here) that would cause a loop in the framework.
这篇关于将列附加到具有动态绑定值的现有数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!