Set the DataKeyNames property of the gridviewMost of the time I use optimistic concurrency (with a check on all fields) to update a database row. While using a gridview to update rows in a table, problems arise when you don’t show or use all database fields of that table in your grid.
Running an automatic update command with optimistic concurrency is bound to fail because the grid cannot supply all original values.

To solve this issue you have to set and extra property and you have to supply some code to the Rowupdating event of the gridview. The property you have to set with the field names that you are not using is the DataKeyNames property of the gridview. For example:


Now you can add the missing information to the OldValues and NewValues collection in the RowUpdating event.

Protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
 IDictionaryEnumerator restoreOldValues = e.Keys.GetEnumerator();
 while (restoreOldValues.MoveNext())
  e.OldValues.Add(restoreOldValues.Key.ToString(),   restoreOldValues.Value.ToString());
  e.NewValues.Add(restoreOldValues.Key.ToString(),   restoreOldValues.Value.ToString());

The gridview now has all the required information to run a successful update.