How to Use ImageButton Columns in GridView in Asp.Net C# VB.Net

In many e-commerce site we need to use product listing page as well as shopping cart page. In most cases we have used GridView control to implement those page. For better look and feel we need to use Image Controls in the GridView Control. So using Image control column in a GridView is an essential job for us. Here in this article I will describe “How we can use ImageButton Control Columns in GridView in Asp.Net C# VB.Net“.

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

How to Use ImageButton 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 ImageButton:

    <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="Image" CommandName="BuyNow" HeaderText="Buy Now" ImageUrl="Images/BuyNow.png" />
    <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 ImageButton:
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 created. Now we need to handle the ImageButton click event. When user click on an ImageButton Control we need to retrieve “Command Name”, “RowIndex” and “ProductID”. By using “Command Name” we can handle multiple ImageButton column of a GridView and if we get the GridView Row DataKeyNames of the corresponding ImageButton 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 ImageButton Click Event:
C# Code:

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        int nRowIndex = Int32.Parse(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 Integer = Int32.Parse(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
One comment on “How to Use ImageButton Columns in GridView in Asp.Net C# VB.Net
  1. Marving says:

    Hi! I have a question about this, how about if i want to display images in the button, and the routes are stored in the database? I thank you in advance

Leave a Reply

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