Modifying a cell in a DataSet

This post also falls under the “I need to remember this” category, because it's not the first time I've run into the situation.  I was running a quick test of something relatively unrelated (the functionality of the RowUpdating event) when I needed to modify a particular element in a DataSet. The line of code I created to do this was

ds.Tables[0].Rows[0].ItemArray[1] = “Test”;

Seems innocuous enough.  And if you're at all familiar with ADO.NET, this would seem to be a reasonable approach.  In fact, Microsoft even says this is the way to do it here (check out the first C# code...the VB.NET code works fine).  Unfortunately, both Microsoft and reason are mistaken. The correct way to update a cell is as follows

ds.Tables[0].Rows[0].Item[1] = “Test”;

or

ds.Tables[0].Rows[0][1] = “Test”;

The reason for fact that setting the element on ItemArray failing has to do with the actual definition of the ItemArray property.  According to the documentation, ItemArray “gets or sets all of the values for a row through an array”.  In other words, ItemArray is intended to be used an array at a time, not an element at a time. In fact, the getter on ItemArray is actually creating a copy of the values in the DataRow (if you need proof, use a tool like Reflector to check out the code).  So when you do the assignment, you're changing the value of a copy of the values in DataRow, not the underlying value itself.  Which, in turn, means that any DataAdapter.Update performed on the DataSet won't see the change.

Just something to keep in mind.