c# - 在 C# 中添加和更新 DataTable 列

标签 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;

      }
    }
  }

}

最佳答案

你应该把你的代码改成这样

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;

      }
    }
  }

}

关于c# - 在 C# 中添加和更新 DataTable 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11765733/

相关文章:

c# - 从 Razor Pages 中的数据库模型填充 TreeView

c# - 在 Foreach 关键字中等待

c# - 理论 : Implementing MSMQ using SSL to send message

c# - CS0234 : The type or namespace name '<namespace2>' does not exist in the namespace '<namespace1>.' (are you missing an assembly reference? )

c# - HttpWebRequest Url 转义

c# - 在特定时间运行流程的最佳方式

c# - Int32 的最短字符串表示

c# - 如何添加到 Listview 项目的特定列?

c# - 将 eval 传递给 javascript

c# - 正则表达式匹配字符串中的 "time"值