gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:59 25 4
gpt4 key购买 nike

我正在尝试向 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com