How to Use Button columns in GridView in Asp.Net C# VB.Net

GridView Control is one of the most popular Control for Asp.Net developers. To represent tabular data GridView is the first choice for us. To make the GridView functional rather than a report we can include different types of columns or fields like Button Control, HyperLink Control etc. Due to the more demand of Button Controls here in this post I will explain “How one can use Asp.Net Button Controls as a column of a GridView Control“.

Related Articles:
1. How to Use LinkButton or HyperLink Columns in GridView in Asp.Net C# VB.Net
2. How to Use ImageButton Columns in GridView in Asp.Net C# VB.Net

Using Button columns in GridView 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 ButtonField:

    <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="button" 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 ButtonField:
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 set. Now we need to handle the Button click event. When user click on a Button Control we need to retrieve “Command Name”, “RowIndex” and “ProductID”. By using “Command Name” we can handle multiple Button column of a GridView and if we get the GridView Row DataKeyNames of the corresponding Button Control we can do everything. Since ProductID is the primary key of our Product Table.

Note: If you click on a ButtonField 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:
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.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, Gridview, VB.Net

Leave a Reply

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