How to fire onClick event of LinkButton inside gridview in asp.net using c#

In this asp.net tutorial you will learn how to fire onclick event of LinkButton inside gridview in asp.net using c#. Normally you can't fire the onclick event of LinkButton which lies inside gridview but in this tutorial we will look how to do this.

Let's have a look over .aspx page in which we have gridview control

.aspx page

<asp:gridview ID="GridView1" runat="server" Width="100%" EnableTheming="false" AutoGenerateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Customer ID">

<ItemTemplate>

<asp:LinkButton ID="lnk_CustomerID" Text='<%# Bind("Customer_ID")%>' runat="server" OnClick="lnk_CustomerID_Click"></asp:LinkButton>

</ItemTemplate>


</asp:TemplateField>

<asp:TemplateField HeaderText="Customer Name">

<ItemTemplate>

<asp:Label ID="lbl_CustomerName" Text='<%# Bind("Customer_Name")%>' runat="server"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Customer Age">

<ItemTemplate>

<asp:Label ID="lbl_CustomerAge" Text='<%# Bind("Customer_Age")%>' runat="server"></asp:Label>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:gridview>

As you can see that I have Link button inside the gridview that in mycase contains the unique values which is Customer ID. Now I want to fire the onclick event of LinkButton to execute some other code, which is to store the Text of LinkButton in a session and then want redirection to the Customer Detail page. Let’s have a look how it can be done.

.cs page

protected void lnk_CustomerID_Click(object sender, EventArgs e)
{
LinkButton link = (LinkButton)sender;
GridViewRow gv = (GridViewRow)(link.Parent.Parent);
LinkButton CustomerID = (LinkButton)gv.FindControl("lnk_CustomerID");
Session["customerid"] = CustomerID.Text;
Response.Redirect("customer_detail.aspx");
}
So this is the way to fire the onclick event of LinkButton inside gridview in asp.net using c#.

Happy Coding...!

Keep Coding...!

1 comments:

  • Anonymous
     

    Hi thanks...
    it worked