I am binding link button with title data in aspgridview and also binding hidden label which holds the ID value. when user click on this link button I would like to access the ID value. This I need because, if user logs in then only I popup detail window else alert message to login for details.
in lnkTitle_Click() event I am trying to access the selected row to find the label control.
GridViewRow grdSelRow = GridView1.SelectedRow;
Label lblID = (Label)grdSelRow.FindControl("lblID");
But I am getting grdSelRow as null.
How to get the selected row when click on linkbutton of gridview?
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");
}
}
来源:https://stackoverflow.com/questions/6295767/getting-selected-row-of-aspgridview-when-click-on-link-button-to-get-hidden-id-v