As I’m still fairly new to ASP.NET, I came across what seemed to be a rather simple task that didn’t seem possible. I wanted to use a GridView control to display information from an SQL query and allow the user to edit the values in the GridView control. My update SQL statement included a WHERE clause referencing the primary key, an identity field. While it was not necessary to display the value to the user, it is necessary to reference the value in order to update the underlying data. I added the column to my GridView and marked it as hidden. To my surprise, any changes to the data in Edit mode were not saved. I checked and re-checked my update query and everything looked right. I set the column back to visible and voilà, the edit worked properly. After scouring google for a solution and wading through numerous posts that suggested using CSS to hide the data, I finally came across this little blurb in the ASP.NET GridView documentation on the MSDN site:
If the Visible property of a column field is set to false, the column is not displayed in the GridView control and the data for the column does not make a round trip to the client. If you want the data for a column that is not visible to make a round trip, add the field name to the DataKeyNames property.
I checked the properties of GridView and surely, no fields were listed in the DataKeyNames property. I added my primary key and removed the column entirely from the GridView. The data was then updated successfully.