Programmatically add LinkButton to a GridView in Asp.Net C# and Vb.Net

← PrevNext →

I have received many queries in the past on how to add LinkButton to a GridView control programmatically. The GridView RowDataBound event is widely used to bind controls to a GridView row at runtime. I’ll use the same event to write my code to dynamically add or bind LinkButton to a GridView control.

Dynamically Add LinkButton to GridView

Related Article: Programmatically Create and Add DropDownList to a GridView Control in Asp.Net - C# and VB

Here in this article we will explore another interesting procedure (besides simply adding a LinkButton). I’ll show how to add a LinkButton to a GridView row based on certain conditions. Conditional manipulations are fun and it helps us understand the procedure clearly.

Therefore, remember we are going to experiment with two different procedures, to add LinkButton to GridView control, dynamically.

1st Procedure - Bind LinkButton using RowDataBound Event

I’ll first add a GridView control in my web page, and assign the columns and rows from code behind. While the page loads for the first time, I’ll create four columns and add few rows to the GridView. The last column however, will not have any header. This is the column were I’ll add the LinkButton control inside GridView’s RowDataBound event.

Also Read: GridView – Highlight a row on mouse over using Asp.Net

The Markup
<!DOCTYPE html>
<html>
<head>
    <title>Dynamically add LinkButton to GridView</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:GridView ID="GridView" 
                Font-Names="Arial" 
                Font-Size="0.75em" 
                CellPadding="5" CellSpacing="0" 
                ForeColor="#333" 
                AutoGenerateColumns="true"
                runat="server">
                
                <HeaderStyle BackColor="#989898" ForeColor="white" />
                
            </asp:GridView>
        </div>
    </form>
</body>
</html>

Related: Bind Stored Procedure data to a GridView using SqlDataSource Web Server Control

Code Behind (C#)
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page 
{
    System.Data.DataTable mytable = new System.Data.DataTable();

    protected void Page_Load(object sender, EventArgs e)
    {
        CreateGrid();
        AddRowsToGrid();

        // NOW BIND THE GRIDVIEW WITH THE DATATABLE.
        GridView.DataSource = mytable;
        GridView.DataBind();
    }

    private void CreateGrid()
    {
        // CREATE A GRID FOR DISPLAYING A LIST OF BOOKS.

        System.Data.DataColumn tColumn = null;
        // TABLE COLUMNS.

        tColumn = new System.Data.DataColumn("Book ID", System.Type.GetType("System.String"));
        mytable.Columns.Add(tColumn);
        tColumn = new System.Data.DataColumn("Name of the Book", System.Type.GetType("System.String"));
        mytable.Columns.Add(tColumn);
        tColumn = new System.Data.DataColumn("Price ($)", System.Type.GetType("System.String"));
        mytable.Columns.Add(tColumn);
        tColumn = new System.Data.DataColumn(" ", System.Type.GetType("System.String"));
        mytable.Columns.Add(tColumn);
    }

    private void AddRowsToGrid()
    {
        // ADD ROWS TO THE DATATABLE.
        mytable.Rows.Add(1, "Computer Architecture", "125.60");
        mytable.Rows.Add(2, "Advanced Composite Material", "50.00");
        mytable.Rows.Add(3, "Asp.Net 4 Blue Book", "80.00");
        mytable.Rows.Add(4, "Strategies Unplugged", "99.99");
        mytable.Rows.Add(5, "Teaching Science", "51.50");
    }

    protected void GridView_RowDataBound(object sender, 
        System.Web.UI.WebControls.GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // CREATE A LinkButton AND IT TO EACH ROW.
            LinkButton lb = new LinkButton();
            lb.ID = "lbBooks";
            lb.Text = "Select";

            e.Row.Cells[3].Controls.Add(lb);
        }
    }
}
Vb.Net
Option Explicit On

Partial Class _Default
    Inherits System.Web.UI.Page

    Dim mytable As New Data.DataTable()

    Protected Sub form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles form1.Load
        If Not IsPostBack Then
            CreateGrid()
            AddRowsToGrid()

            ' NOW BIND THE GRIDVIEW WITH THE DATATABLE.
            GridView.DataSource = mytable
            GridView.DataBind()
        End If
    End Sub

    Private Sub CreateGrid()
        ' CREATE A GRID FOR DISPLAYING A LIST OF BOOKS.

        Dim tColumn As Data.DataColumn          ' TABLE COLUMNS.

        tColumn = New Data.DataColumn("Book ID", System.Type.GetType("System.String"))
        mytable.Columns.Add(tColumn)
        tColumn = New Data.DataColumn("Name of the Book", System.Type.GetType("System.String"))
        mytable.Columns.Add(tColumn)
        tColumn = New Data.DataColumn("Price ($)", System.Type.GetType("System.String"))
        mytable.Columns.Add(tColumn)
        tColumn = New Data.DataColumn(" ", System.Type.GetType("System.String"))
        mytable.Columns.Add(tColumn)
    End Sub

    Private Sub AddRowsToGrid()
        ' ADD ROWS TO THE DATATABLE.

        mytable.Rows.Add(1, "Computer Architecture", "125.60")
        mytable.Rows.Add(2, "Advanced Composite Material", "50.00")
        mytable.Rows.Add(3, "Asp.Net 4 Blue Book", "80.00")
        mytable.Rows.Add(4, "Strategies Unplugged", "99.99")
        mytable.Rows.Add(5, "Teaching Science", "51.50")
    End Sub

    Protected Sub GridView_RowDataBound(ByVal sender As Object, _
        ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView.RowDataBound

        If e.Row.RowType = DataControlRowType.DataRow Then

            ' CREATE A LinkButton AND IT TO EACH ROW.
            Dim lb = New LinkButton()
            lb.ID = "lbBooks"
            lb.Text = "Select"

            e.Row.Cells(3).Controls.Add(lb)
            
        End If
    End Sub
End Class

Also Read: How to Bind a DropDownList to a Database table in GridView? - C#

2nd Procedure

Add LinkButton using A Condition

In the second procedure, I’ll add a Button control on the web page. On button’s Click event, I’ll create and bind the LinkButton to the GridView. In addition, I’ll now set a condition and add the LinkButton to each row, if the Price is greater or equal to $80.

Simply, add the below code in the Markup section, just after the GridView. It’s the Asp.Net Button control, attached with the OnClick event.

<asp:Button ID="bt" runat="server" Text="Add Link" OnClick="bt_Click" />

You can now remove onrowdatabound="GridView_RowDataBound from the GridView in this example. Since, I'll add the LinkButton using the Button OnClick event.

Code Behind - Button Click Event (C#)
protected void bt_Click(object sender, EventArgs e)
{
    foreach (GridViewRow row in GridView.Rows)
    {
        if (row.RowType == DataControlRowType.DataRow)
        {
            // ADD LINK BUTTON IF PRICE >= $80

            if (double.Parse(row.Cells[2].Text) >= 80)
            {
                LinkButton lb = new LinkButton();
                lb.ID = "lbBooks";
                lb.Text = "Add";

                row.Cells[3].Controls.Add(lb);
            }
        }
    }
}
Vb.Net
Protected Sub bt_Click(ByVal sender As Object, ByVal e As EventArgs)

    For Each row As GridViewRow In GridView.Rows
        If row.RowType = DataControlRowType.DataRow Then

            ' ADD LINK BUTTON IF PRICE MORE THAN $80.
            If Val(row.Cells(2).Text) >= 80 Then

                Dim lb As New LinkButton()
                lb.ID = "lbBooks"
                lb.Text = "Add"

                row.Cells(3).Controls.Add(lb)
            End If
        End If
    Next
End Sub

Happy Coding. 🙂

← PreviousNext →