C# 替换数据列中的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12951411/
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
Replace value in DataColumn
提问by dbd
How to replace column value when looping rows?
循环行时如何替换列值?
My DataTable has two columns, I want to replace the value of the first column on every row. I'm unable to get or set column value. So far I only manege to access DefaultValue and ColumnName etc.
我的 DataTable 有两列,我想替换每一行第一列的值。我无法获取或设置列值。到目前为止,我只能访问 DefaultValue 和 ColumnName 等。
Even if creating new DataColumn(), I'm not able to set its value.
即使创建新的 DataColumn(),我也无法设置其值。
Feels like I'm missing some fundamental stuff here...
感觉我在这里遗漏了一些基本的东西......
foreach (var row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
// column Unable to get or set value
}
}
Running .NET Framework 3.5, should I use linq?
运行 .NET Framework 3.5,我应该使用 linq 吗?
采纳答案by Tim Schmelter
Since DataTable.Rowsimplements only IEnumerableand not IEnumerable<T>you need to cast it to DataRowin the foreachand you cannot use var:
由于DataTable.Rows仅实现IEnumerable而不是IEnumerable<T>您需要将其强制转换为DataRowinforeach并且您不能使用 var:
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
row.SetField(column, newValue);
}
}
回答by andy
for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++)
{
dataTable.Rows[rowIndex][0] = "Replacing value";
}
回答by mrt181
You could do this
你可以这样做
foreach (DataRow row in table.Rows)
{
row.SetField(table.Columns.Cast<DataColumn>().Single(column => column.Ordinal == 0), "new");
}

