GridView: Get datakey of the row on button click

依然范特西╮ 提交于 2019-12-07 13:02:59

问题


How can I get a value of the DataKeyName of a GridView Row when I have a button inside a row that have an OnClick event. In my OnClick event of my button I want to get a the DataKeyName of the row where the button resides.

Is this possible?

<asp:GridView ID="myGridView" run="server">
     <Columns>
          <asp:TemplateField HeaderText="Column 1">
               <ItemTemplate>
                   ... bunch of html codes
                   <asp:Button ID="myButton" UseSubmitBehavior="false" runat="server" Text="Click Me" onclick="btnClick_Click" />
               </ItemTemplate>
           </asp:TemplateField>
     </Columns>
</asp:GridView>

In my codebehind

protected void btnClick_Click(object sender, EventArgs e)
{
    // How can I get the DataKeyName value of the Row that the Button was clicked?
}

回答1:


When I'm working with a GridView, I usually do not use the OnClick event for buttons. Instead, I use the OnRowCommand event on the GridView, and bind data to the CommandArgument property of the button. You can retrieve the command argument from the GridViewCommandEventArgs parameter of the event handler.

You can use the CommandName parameter to bind an arbitrary string to distinguish between any different kinds of buttons you have. Note that some command names are already used for other events, such as "Edit", "Update", "Cancel", "Select" and "Delete".

Update:

Here is an example, assuming the data key is called "ID":

<asp:GridView ID="myGridView" runat="server" OnRowCommand="myGridView_RowCommand">
     <Columns>
          <asp:TemplateField HeaderText="Column 1">
               <ItemTemplate>
                   ... bunch of html codes
                   <asp:Button ID="myButton" runat="server" Text="Click Me" CommandName="ClickMe" CommandArgument='<%# Eval("ID") %>' />
               </ItemTemplate>
           </asp:TemplateField>
     </Columns>
</asp:GridView>

And in the code-behind:

protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
    var datakey = e.CommandArgument;
    // ...
}



回答2:


You can bind the key to the CommandArgument property of the Button, and consume (sender as Button).CommandArgument property in the code



来源:https://stackoverflow.com/questions/3544507/gridview-get-datakey-of-the-row-on-button-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!