在C#中添加和更新DataTable列

时间:2012-08-01 18:57:48

标签: c# .net

我正在尝试将列添加到DataTable。

我可以很好地添加列。但是,当我遍历这些新列的行设置值时,它不会更新DataRow.ItemArray。这是我的代码:

private void UpdateTabularDataTable(SqlConnection connection)
{
      // when I add these columns, it works fine.
      var rejectedColumn = table.Columns.Add(Constants.RejectedUiColumnName, typeof(bool));
      var rejectedReasonColumn = table.Columns.Add(Constants.RejectedReasonUiColumnName, typeof(string));

      foreach (var row in table.Rows.Cast<DataRow>())
      {
        var contourId = (Guid)row.ItemArray[0];

        // this is a Dictionary of objects which are rejected.  The others are accepted.
        string rejectedReason;
        var isRejected = _rejectedParticleReasonHolder.TryGetValue(contourId.ToString(), out rejectedReason);

        // these assignments don't work.  There's no exception; they 
        // just don't update the relevant values on the object.
        // Also, I verified that the Ordinal values are correct.
        row.ItemArray[rejectedColumn.Ordinal] = isRejected;
        row.ItemArray[rejectedReasonColumn.Ordinal] = rejectedReason;

      }
    }
  }

}

2 个答案:

答案 0 :(得分:3)

你应该改变你的代码看起来像这样

private void UpdateTabularDataTable(SqlConnection connection)
{
      table.Columns.Add(Constants.RejectedUiColumnName, typeof(bool));
      table.Columns.Add(Constants.RejectedReasonUiColumnName, typeof(string));

      foreach (var row in table.Rows.Cast<DataRow>())
      {
        var contourId = (Guid)row.ItemArray[0];

        // this is a Dictionary of objects which are rejected.  The others are accepted.
        string rejectedReason;
        var isRejected = _rejectedParticleReasonHolder.TryGetValue(contourId.ToString(), out rejectedReason);

        row[Constants.RejectedUiColumnName] = isRejected;
        row[Constants.RejectedReasonUiColumnName] = rejectedReason;

      }
    }
  }

}

答案 1 :(得分:2)

我的一位同事发现了这个问题。不应直接访问row.ItemArray。相反,我使用row[columnName] = value来修改列值。