# Wednesday, 19 May 2004

Are you using a hidden column in your DataGrids to store the ID of rows? I was until recently when I discovered that you can specify a field on the DataGrid which contains the keys. It goes a little something like this

<asp:DataGrid id="MyGrid" runat="server" DataKeyField="TheFieldInDataSourceWhichContainsTheUniqueKey">...

In code you can retrieve the key in a command event handler or something similar like this

private void MyGrid_EditCommand( object sender, DataGridCommandEventArgs e )
  int id = ( int ) MyGrid.DataKeys[ e.Item.ItemIndex ];

Neat little trick which keeps your DataGrids a little bit cleaner :)

You can of course use any data type as the data key, just change the cast to the appropriate type and you're all set :)

Friday, 09 June 2006 22:41:26 (Romance Daylight Time, UTC+02:00)
Thank you, I spent 2 days wondering why my data grid had no 'datakeys' until I came across this post.
Wednesday, 12 December 2007 14:11:51 (Romance Standard Time, UTC+01:00)
u look like a serial killer
Comments are closed.