1

I want to fetch the DataKey of the Selected Row of GridView on button click.

1
  • are you still look for an answer to this question?
    – cgreeno
    Feb 3, 2009 at 16:07

2 Answers 2

2

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.

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();
}
2
  • While I think Chris' answer is great (I do this myself), I'd set the CommandArgument field to be the RowIndex and then set the object's Id or any other pertinent data, in the DataKeys for the row. That way you have the RowIndex quickly available and can easily access any needed data.
    – Dillie-O
    Feb 5, 2009 at 17:40
  • That is a good idea, I have always just manipulated the CommandArgument to get what I needed out of the row, I like the idea of a direct reference to the row however. Cheers!
    – cgreeno
    Feb 5, 2009 at 17:49
0

Use the SelectedDataKey property of the GridView:

DataKey currentKey = myGridView.SelectedDataKey;
1
  • Then you'll probably have to give more info on the problem. For example, does your GridView have AutoGenerateSelectbutton set to true? Are you using Select buttons this generates? Jan 27, 2009 at 11:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.