获取GridView的RowCommand DataKey值 [英] Get DataKey values in GridView RowCommand

查看:340
本文介绍了获取GridView的RowCommand DataKey值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 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?

这似乎是工作,但我不喜欢的演员到的LinkBut​​ton (如果其他一些命令,触发事件是什么?),我不是太充满信心 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆