2
votes

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?

3
you should use linq whenever possible - mrt181
To my knowledge linq requires IEnumerable<T> and therefor linq is not applicable in this case? - dbd

3 Answers

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

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);
    }
}
2
votes

You could do this

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