How to Use LinkButton or HyperLink Columns in GridView in Asp.Net C# VB.Net

By using GridView we can represent data in many ways. For reporting purposes we can use tabular data representation. But if we need to do some operation on GridView then we need to add server side controls to interact with GridView. There are a lot of reason to use LinkButton or HyperLink column in GridView. For example if we want to display a product details page then we can easily navigate to product details page from product listing page by clicking on the Link Button or HyperLink. In this article I will explain How we can use LinkButton or HyperLink Columns in GridView in Asp.Net C# VB.Net. I will also describe how we can pass query string value based on DataKeyNames to another page based on GridView Row selection.

Related Articles:
1. How to Use Button columns in GridView in Asp.Net C# VB.Net
2. How to Use ImageButton Columns in GridView in Asp.Net C# VB.Net

How to Use LinkButton or Hyperlink columns in GridView in Asp.Net Csharp VB.Net

To do the Example first create the Below Table:

CREATE TABLE [dbo].[Product](
    [ProductID] [bigint] NOT NULL,
    [ProductName] [varchar](max) NOT NULL,
    [ProductDescription] [varchar](max) NULL,
    [ProductPrice] [int] NULL
    [ProductID] ASC

Insert Some Data Like Below:

Modify Web.Config File to connect to SQL Server:

    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

GridView Control HTML Code with LinkButton:

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" 
        DataKeyNames="ProductID" HeaderStyle-BackColor="CornflowerBlue" 
        HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5" 
        <asp:BoundField DataField="ProductName"  HeaderText="Product"/>
        <asp:BoundField DataField="ProductDescription"  HeaderText="Description"/>
        <asp:BoundField DataField="ProductPrice"  HeaderText="Price"/>
        <asp:ButtonField ButtonType="Link" CommandName="MoreDetail" HeaderText="More Details" Text="More Details" />
    <br />
    <hr />
    <asp:Label ID="Label1" runat="server" Text=""></asp:Label><br />
    <asp:Label ID="Label2" runat="server" Text=""></asp:Label><br />
    <asp:Label ID="Label3" runat="server" Text=""></asp:Label>

Now Bind the GridView Control including LinkButton:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            string consString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(consString))
                SqlCommand cmd = new SqlCommand("SELECT * FROM [Product]", conn);
                cmd.CommandType = CommandType.Text;
                SqlDataReader drStudents = cmd.ExecuteReader();
                GridView1.DataSource = drStudents;

Note: Don’t forget to add “System.Data”, “System.Data.SqlClient” & “System.Configuration” namespaces.

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim consString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
            Using conn As New SqlConnection(consString)
                Dim cmd As New SqlCommand("SELECT * FROM [Product]", conn)
                cmd.CommandType = CommandType.Text
                Dim drStudents As SqlDataReader = cmd.ExecuteReader()
                GridView1.DataSource = drStudents
            End Using
        End If
    End Sub

Note: Don’t forget to add “System.Data”, “System.Data.SqlClient” & “System.Configuration” namespaces.

Everything ready. Now we need to handle the LinkButton click event. When user click on a LinkButton Control we need to retrieve “Command Name”, “RowIndex” and “ProductID”. By using “Command Name” we can handle multiple LinkButton column of a GridView and if we get the GridView Row DataKeyNames of the corresponding LinkButton Control we can do everything. Since ProductID is the primary key of our Product Table.

Note: If you click on a LinlButton or HyperLink then the GridView raise an event named “RowCommand”. So now we need to implement the GridView RowCommand Event to get the “Command Name”, “RowIndex” and “DataKeyNames”.

Implement GridView RowCommand Event to handle LinkButton Click Event:
C# Code:

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        Int32 nRowIndex = Convert.ToInt32(e.CommandArgument.ToString());
        Int32 nProductID = Convert.ToInt32(GridView1.DataKeys[nRowIndex].Value);

        Label1.Text = "Command Name: " + e.CommandName;
        Label2.Text = "Row Index: " + nRowIndex;
        Label3.Text = "Product ID: " + nProductID;

VB.Net Code:

    Protected Sub GridView1_RowCommand(sender As Object, e As GridViewCommandEventArgs)
        Dim nRowIndex As Int32 = Convert.ToInt32(e.CommandArgument.ToString())
        Dim nProductID As Int32 = Convert.ToInt32(GridView1.DataKeys(nRowIndex).Value)

        Label1.Text = "Command Name: " & Convert.ToString(e.CommandName)
        Label2.Text = "Row Index: " & nRowIndex
        Label3.Text = "Product ID: " & nProductID
    End Sub

Now run the project. Since you got the primary key, you can do everything now.

Navigation using LinkButton or HyperLink column in GridView:
We can also navigate through LinkButton or HyperLink column to another page. We can also transfer data from GridView Row to another page by using Query String. To do the example add a page in your project and named it “ProductDetails.aspx”.

Modify the LinkButton or HyperLink for Navigation:
Add the below column in your GridView Control:

<asp:HyperLinkField  Text="More Details"
          HeaderText="More Details" 
          DataNavigateUrlFormatString="ProductDetails.aspx?ProductID={0}" />

If you want to transfer more Query String Values use the below Code:

      DataNavigateUrlFields="ProductID, ProductPrice" Text="More Details"
      HeaderText="More Details" />

Now read Transferred Query String Values from ProductDetails.aspx page:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            Response.Write("Product ID="+Request.QueryString["ProductID"].ToString());

                Response.Write("Product Price=" + Request.QueryString["ProductPrice"].ToString());

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Response.Write("Product ID=" & Request.QueryString("ProductID").ToString())

            If Request.QueryString("ProductPrice") IsNot Nothing Then
                Response.Write("Product Price=" & Request.QueryString("ProductPrice").ToString())
            End If
        End If

    End Sub

Hope now everything clear. If not please download code sample from below:

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code