views:

1043

answers:

1

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.

+2  A: 

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 = this.grid.DataKeys[rowIndex]["myKey"]);
Elph
I ended up using the CommandArgument, but I can see how this solution would also work.
Farinha
I think is best when you need to acces more than only one value...
Elph