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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…