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.
CommandSource; GridViewRow gvr = (GridViewRow)lb. NamingContainer; int id = (int)grid. DataKeys[gvr. RowIndex].
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.
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With