The problem is that when you click a button in a GridView, the row will only be a Clicked Row and not a SelectedRow
. If you wanna make it the SelectedRow you have to specify CommandName="Select"
in the Button's markup.
Here are two methods for accomplish your requirement.
Wiring up an onclick event for the LinkButton inside ItemTemplate
Markup
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
Text="Click1"
OnClick="LinkButton1_Click"/>
</ItemTemplate>
</asp:TemplateField>
Code-behind
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton) sender).NamingContainer as GridViewRow;
Label lblID = (Label)clickedRow.FindControl("lblID");
}
Using RowCommand to catch the LinkButton click.
Markup
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton2" runat="server"
Text="Click2"
CommandName="MyCustomCommand"/>
</ItemTemplate>
</asp:TemplateField>
Code-behind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName.Equals("MyCustomCommand"))
{
GridViewRow clickedRow = ((LinkButton)e.CommandSource).NamingContainer as GridViewRow;
Label lblID = (Label)clickedRow.FindControl("lblID");
}
}