I want to fetch the DataKey of the Selected Row of GridView on button click.
A:
Use the SelectedDataKey property of the GridView:
DataKey currentKey = myGridView.SelectedDataKey;
Vojislav Stojkovic
2009-01-27 10:08:21
its giving null exception
2009-01-27 10:11:15
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?
Vojislav Stojkovic
2009-01-27 11:41:12
+2
A:
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();
}
cgreeno
2009-01-27 10:10:29
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
2009-02-05 17:40:52
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
2009-02-05 17:49:45