我想在按钮点击时获取GridView所选行的DataKey。
答案 0 :(得分:2)
我个人会在模板字段中这样做:
<asp:TemplateField>
<ItemTemplate>
//EDIT: after a comment it is suggested that you pass the RowIndex as the command argument which would provide access to the entire row
<asp:LinkButton ID="btnCopy" runat="server"CausesValidation="False"CommandName="MyCommandButton"CommandArgument='<%# Eval("MyDataKeyOrWhateverIWanteverIWantFromTheBindingSource")%>'>
</ItemTemplate>
</asp:TemplateField>
<强>代码隐藏强>
protect void MyCommandButton(Object sender,CommandArgument e)
{
int DataKeyOrPK=int32.Parse(e.CommandArgument.ToString());
}
你的其他选择是:
<asp:gridview id="myGrid" runat="server"
width=100% datakeynames="Myid"
autogeneratecolumns=false
onSelectedIndexChanged="MyEvent">
<asp:templatefield headertext="Choose your dream home">
<itemtemplate>
<asp:linkbutton runat="server" commandname="select" text='<%# Eval ( "Whatever" ) %>' />
</itemtemplate>
</asp:templatefield>
注意上面的commandname =“select”。
数据绑定控件识别某些命令名称并自动引发和处理控件的相应事件。识别以下命令名称: 取消,删除,编辑,插入,新建,翻页,选择,排序和更新。 Reference
<强>代码隐藏强>
private void MyEvent(Object sender, EventArgs e)
{
string id = myGrid.SelectedDataKey.Value.ToString();
}
答案 1 :(得分:0)
使用GridView的SelectedDataKey属性:
DataKey currentKey = myGridView.SelectedDataKey;