C# – Trouble with updating DataRow in C#


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:


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

Any help would be appreciated! thanks!

Best Solution

Simply change:

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


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.