Here is a simple way to store hidden data in a GridView.

You can’t just set a BoundField Visible=”false”, because then the data isn’t bound to the GridView. In other words trying to read cells in that column will return an empty string which is pretty useless.

People have suggested different solutions to this problem. To mention a few.. :

  • Use CSS to effectively hide the columns
  • Handle the GridView’s RowDataBound event, and hide the cells programmatically there.
  • Use a HiddenField inside an ItemTemplate

However a much simpler solution is built into GridView from the start. It relies on setting the GridView’s DataKeyNames property.

<asp:gridview id="ExampleGridView" runat="server datakeynames="PrimaryKeyDataValueName">

Now retrieving the primary key value is simply done by:

int rowIdx = ExampleGridView.SelectedRow.RowIndex;
DataKey _dataKey = ExampleGridView.DataKeys[rowIdx];
int primaryKey = (int)_dataKey.Value;

Seems you can store more than one value with datakeynames, eg. other columns you want to keep hidden. In that case you will have to modify the code. For most simple scenarios this technique works great, but as always: even if the values are visually hidden they can still be easily retrieved. So at least encrypt sensitive data – or even better keep all sensitive data on the server side.

Advertisements