在C#中更新DataRow有问题

我有一个非常简单的C#DataTable问题,我似乎无法解决这个问题。 它看起来如此紧张,但我必须遗漏一些东西。

我希望有人可以向我解释为什么我无法更新DataTable中的单元格值,如下所示:

码:

DataTable t = new DataTable(); t.Columns.Add("MyCol"); t.Rows.Add("old value"); t.Rows[0].ItemArray[0] = "new value"; t.AcceptChanges(); dataGridView1.DataSource = t; //did not work. still reads "old value" 

任何帮助,将不胜感激! 谢谢!

简单地改变:

 t.Rows[0].ItemArray[0] = "new value"; 

 t.Rows[0][0] = "new value"; 

而已!

编辑(补充说明):

不跟踪对ItemArray元素的更改,因此数据表值中不会反映任何更改(原始问题中的代码)

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

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

在这种情况下,将跟踪更改,并获得预期结果。

回答你的问题

你应该这样做

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

根据MSDN,

您可以使用此属性通过数组设置或获取此行的值。 如果使用此属性设置值,则数组必须具有与列集合相同的大小和顺序。 在ItemArray中传递null表示没有指定任何值。

你试过以下吗?

 ... dataGridView1.DataSource = null; // set it to null before it set to a new one. dataGridView1.DataSource = t;