Trouble with updating DataRow in C#

人走茶凉 提交于 2019-12-05 02:29:24

问题


I have a very simple C# DataTable problem that I cannot seem to wrap my head around; it seems so strait forward but I must be missing something.

I was hoping that someone could explain to me why I'm unable update a cell value in a DataTable like shown below:

Code:

    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"

Any help would be appreciated! thanks!


回答1:


Simply change:

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

to

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

That's it!

EDIT (Added explaination):

Changes to ItemArray elements are not tracked, so no changes are reflected in the datatable values (code in the original question)

However you can use ItemArray to change all the row at once, like this:

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

In this case the changes are tracked, and you get the expected result.




回答2:


To answer you question

you should do like this

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

according to MSDN,

You can use this property to set or get values for this row through an array. If you use this property to set values, the array must have the same size and ordering as the column collection. Passing null in the ItemArray indicates that no value was specified.




回答3:


Have you tried the following?


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


来源:https://stackoverflow.com/questions/9815026/trouble-with-updating-datarow-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!