Getting selected row of aspgridview when click on link button to get hidden ID value

混江龙づ霸主 提交于 2019-12-02 18:16:53

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");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!