# Wednesday, May 19, 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, June 09, 2006 10:41:26 PM (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.
DBD
Wednesday, December 12, 2007 2:11:51 PM (Romance Standard Time, UTC+01:00)
u look like a serial killer
me
Comments are closed.