Home

SiteMap

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

← PrevNext →

Last updated: 23rd May 2024

I have shared two different methods (procedures) in this tutorial showing how to add or bind LinkButton to GridView control dynamically using C# and VB.
See this demo

We will explore another interesting procedure in this tutorial (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.

1st Procedure - Bind LinkButton using RowDataBound Event

I’ll first add a GridView control in my web page, and add 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.

The Markup

Add a GridView control.

<!DOCTYPE html>
<html>
<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>
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);
    }

    // Add some data to the grid.
    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
See this demo

2nd Procedure

Add LinkButton on some 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

Dynamically Add LinkButton to GridView

← PreviousNext →