19

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?

naveen
  • 48,336
  • 43
  • 154
  • 235
NMM
  • 213
  • 1
  • 2
  • 6

1 Answers1

25

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");
    }
}
naveen
  • 48,336
  • 43
  • 154
  • 235
  • 1
    +1 @Naveen for specifying "If you wanna make it the SelectedRow you have to specify CommandName="Select" in the Button's markup" – Ram Jan 17 '13 at 08:30
  • @Naveen how do you mark selection before you show a javascript confirm in case of gridview? if i click on cancel in the confirm i do not see the current row selected nor when do i see the selected row before i am shown the confirm popup. – Ram Feb 22 '13 at 03:24
  • @dasariramacharanprasad: could you elaborate and ask it as a qiestion. i did not fully understand. – naveen Feb 22 '13 at 13:05
  • @naveen How do we mark grid row selection using javascript? Can we call any Asp.net javascript method / or any way to make a row as selected but dont want to perform any action on that button click in that row (since user cancelled in the javascript confirm popup)? – Ram Mar 01 '13 at 08:19