My Technical Notes

Wednesday, 17 April 2013

Getting the Database ID from a Row in a GridView in RowCommand event

The following code does the trick:


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int rowIndex = ((e.CommandSource as Control).Parent.Parent as GridViewRow).RowIndex;
    object rowDataKey = (sender as GridView).DataKeys[rowIndex].Value;
}

Note that the rowDataKey needs to be cast to the type of the ID field e.g. Guid, int etc.

The above code can be re-written using the GetParentControls extension method as so:


protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int rowIndex = (e.CommandSource as Control).GetParentControls().OfType<GridViewRow>().First().RowIndex;
    object rowDataKey = (sender as GridView).DataKeys[rowIndex].Value;
}

No comments: