Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DataKey values in GridView RowCommand

I have a GridView with an associated DataKey, which is the item ID. How do I retrieve that value inside the RowCommand event?

This seems to work, but I don't like the cast to LinkButton (what if some other command is firing the event?), and I'm not too confident about the NamingContainer bit.

LinkButton lb = (LinkButton)e.CommandSource; GridViewRow gvr = (GridViewRow)lb.NamingContainer; int id = (int)grid.DataKeys[gvr.RowIndex].Value; 

I'm aware that I could instead pass that ID as the CommandArgument, but I chose to use DataKey to give me more flexibility.

I'm also aware that it's possible to use a hidden field for the ID, but I consider that a hack that I don't want to use.

like image 849
Farinha Avatar asked May 12 '10 11:05

Farinha


People also ask

How to get the DataKey value of GridView RowCommand?

CommandSource; GridViewRow gvr = (GridViewRow)lb. NamingContainer; int id = (int)grid. DataKeys[gvr. RowIndex].

How to get DataKey value of selected row in GridView on button click?

Getting the DataKeys value for a particular GridView Row Inside the Button click event handler, first the GridView Row is determined using the NamingContainer property and then finally the Row Index is determined. Using the Row Index, the DataKeys array is accessed and the value of the Column is fetched.


1 Answers

I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.

On the Button:

CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' 

On the Server Event

int rowIndex = int.Parse(e.CommandArgument.ToString()); string val = (string)this.grid.DataKeys[rowIndex]["myKey"]; 
like image 73
Elph Avatar answered Oct 02 '22 08:10

Elph