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

查看:30
本文介绍了在 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 使用隐藏字段,但我认为这是一种我不想使用的 hack.

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天全站免登陆