获取GridView的RowCommand DataKey值 [英] Get DataKey values in GridView RowCommand
问题描述
我有一个 GridView控件
与相关的 DataKey
,这是项ID。
我如何获取 RowCommand
事件中的价值?
I have a GridView
with an associated DataKey
, which is the item ID.
How do I retrieve that value inside the RowCommand
event?
这似乎是工作,但我不喜欢的演员到的LinkButton
(如果其他一些命令,触发事件是什么?),我不是太充满信心 NamingContainer
位。
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;
我知道,我可以代替传递ID为 CommandArgument
,但我选择使用 DataKey
给我更多的灵活性。
I'm aware that I could instead pass that ID as the CommandArgument
, but I chose to use DataKey
to give me more flexibility.
我也知道,它可能使用隐藏域的ID,但我认为,我不希望有一个黑客使用。
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.
推荐答案
我通常通过CommandArgument通过rowIndex位置,并用它来检索DataKey值我想要的。
I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.
按钮:
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
在服务器事件
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];
这篇关于获取GridView的RowCommand DataKey值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!