C# 在按钮上获取 GridView 的当前选定行 单击
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/482842/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the Current Selected Row of GridView on a button Click
提问by
I want to fetch the DataKey of the Selected Row of GridView on button click.
我想在单击按钮时获取 GridView 选定行的 DataKey。
回答by Vojislav Stojkovic
Use the SelectedDataKey property of the GridView:
使用 GridView 的 SelectedDataKey 属性:
DataKey currentKey = myGridView.SelectedDataKey;
回答by cgreeno
I would Personal do it in a Template Field Like so:
我个人会在模板字段中这样做:
<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>
CodeBehind
代码隐藏
protect void MyCommandButton(Object sender,CommandArgument e)
{
int DataKeyOrPK=int32.Parse(e.CommandArgument.ToString());
}
You other option would be:
您的其他选择是:
<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>
Note the commandname="select" above.
注意上面的 commandname="select"。
Data-bound controls recognize certain command names and automatically raise and handle the appropriate events for the control. The following command names are recognized: Cancel, Delete, Edit, Insert, New, Page, Select, Sort and Update. Reference
数据绑定控件识别某些命令名称并自动引发和处理控件的适当事件。可识别以下命令名称: 取消、删除、编辑、插入、新建、页面、选择、排序和更新。参考
Codebehind
代码隐藏
private void MyEvent(Object sender, EventArgs e)
{
string id = myGrid.SelectedDataKey.Value.ToString();
}