替换DataColumn中的值[英] Replace value in DataColumn

本文是小编为大家收集整理的关于替换DataColumn中的值的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

循环行时如何替换列值?

我的数据表有两个列,我想替换每个行上第一列的值. 我无法获得或设置列值.到目前为止,我只操纵访问DefaultValue和columnName等.

即使创建新的datacolumn(),我也无法设置其值.

感觉我在这里错过了一些基本的东西...

        foreach (var row in dataTable.Rows)
        {
            foreach (DataColumn column in dataTable.Columns)
            {
                // column Unable to get or set value
            }

        }

运行.NET框架3.5,我应该使用Linq?

推荐答案

因为DataTable.Rows仅实现IEnumerable而不是IEnumerable<T>您需要在foreach中施放DataRow,并且不能使用var:

foreach (DataRow row in dataTable.Rows)
{
    foreach (DataColumn column in dataTable.Columns)
    {
        row.SetField(column, newValue);
    }
}

其他推荐答案

for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++)
{
  dataTable.Rows[rowIndex][0] = "Replacing value";
}

其他推荐答案

您可以做这个

foreach (DataRow row in table.Rows)
{
    row.SetField(table.Columns.Cast<DataColumn>().Single(column => column.Ordinal == 0), "new");
}

本文地址:https://www.itbaoku.cn/post/1556744.html

问题描述

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.

Even if creating new DataColumn(), I'm not able to set its value.

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?

推荐答案

Since DataTable.Rows implements only IEnumerable and not IEnumerable<T> you need to cast it to DataRow in the foreach and you cannot use var:

foreach (DataRow row in dataTable.Rows)
{
    foreach (DataColumn column in dataTable.Columns)
    {
        row.SetField(column, newValue);
    }
}

其他推荐答案

for (int rowIndex = 0; rowIndex < dataTable.Rows.Count; rowIndex++)
{
  dataTable.Rows[rowIndex][0] = "Replacing value";
}

其他推荐答案

You could do this

foreach (DataRow row in table.Rows)
{
    row.SetField(table.Columns.Cast<DataColumn>().Single(column => column.Ordinal == 0), "new");
}