gpt4 book ai didi

c# - 更新 DataTable 中的值不起作用

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

我有这样的代码:

DataTable dt = new DataTable();
// (...) getting data, displaying on DataGridView - all works fine

int columns = dt.Columns.Count; // getting column count

foreach (DataRow row in dt.Rows)
{
for (int c = 0; c < columns; c++) // c is column index
{
// all old values are positive for debugging
double oldVal = Convert.ToDouble(row.ItemArray[c]);

// new values should become negative
double newVal = oldVal * -1;

row.ItemArray[c] = newVal; // im trying to update value like this

// THIS SHOWS POSITIVE NUMBERS (NOT UPDATED)
this.Text = row.ItemArray[c].ToString(); // this is simple debug

}
}

这有点复杂,我简化了代码。

为什么我的值没有更新?

稍后添加:

还有一点很重要。此数据来自数据库 View ,而不是表。当然,我想更改我的 DataTable 对象中的数据,而不是数据库中的数据。

最佳答案

最后这样做

dt.AcceptChanges();

这将提交自上次调用 AcceptChanges() 以来对此表所做的所有更改。

        DataTable dt = new DataTable();
// (...) getting data, displaying on DataGridView - all works fine

int columns = dt.Columns.Count; // getting column count

foreach (DataRow row in dt.Rows)
{
foreach (DataColumn c in dt.Columns)
{
// all old values are positive for debugging
double oldVal = Convert.ToDouble(row[c]);

// new values should become negative
double newVal = oldVal * -1;

row[c] = newVal; // im trying to update value like this

// THIS SHOWS POSITIVE NUMBERS (NOT UPDATED)
this.Text = row[c].ToString(); // this is simple debug
}
}

dt.AcceptChanges();

编辑(添加说明):

不会跟踪对 ItemArray 元素的更改,因此不会在数据表值中反射(reflect)任何更改

但是您可以使用 ItemArray 一次更改所有行,如下所示:

dt.Rows[0].ItemArray = new object[] {"new value"};

在这种情况下,更改被跟踪,并反射(reflect)在数据表中。

关于c# - 更新 DataTable 中的值不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16195567/

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