In this article, we'll explore how to display binary images in a GridView control in an ASP.NET Web Application. The GridView control is widely used for displaying and manipulating data on web pages. To achieve this task, we have two common approaches: using a handler or converting images to Base64 format. We'll cover both methods in this post, and at the end, you can download the source code.

We'll start by adding a FileUpload control and a button to the WebForm, along with a GridView for displaying the images. When the Upload button is clicked, we'll upload the image files into the database in binary format. Later, we'll retrieve and display the uploaded images in the ASP.NET GridView.

Display the Images(Binary Image) GridView from SQL server By Converting Image to Base64 Data Image

For that, I have created a Students table in SQL database which store in information from our Web Application.

Sql Script:

CREATE TABLE [dbo].[Students](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Name] [nvarchar](150) NULL,
    [City] [nvarchar](500) NULL,
    [ProfilePicture] [varbinary](max) NULL,
    [PictureName] [nvarchar](150) NULL,
 CONSTRAINT [PK_Students_1] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

So let’s create an empty website and add a webform.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table class="auto-style1">
                <tr>
                    <td colspan="2">
                        <fieldset>
                            <legend>Add Students</legend>
                            <asp:TextBox ID="txtname" runat="server" placeholder="Name"></asp:TextBox>
                            <br />
                            <br />
                            <asp:TextBox ID="txtcity" runat="server" placeholder="City"></asp:TextBox>
                            <br />
                            <br />
                            <asp:FileUpload ID="FileUpload1" runat="server" />
                            <br />
                            <br />
                            <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" Width="600px"  GridLines="None" Height="200px" OnRowDataBound="GridView1_RowDataBound">
                            <AlternatingRowStyle BackColor="White" />
                            <Columns>
                                <asp:TemplateField HeaderText="Name">
                                    <ItemTemplate>
                                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="City">
                                    <ItemTemplate>
                                        <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Image Name">
                                    <ItemTemplate>
                                        <asp:Label ID="lblImageName" runat="server" Text='<%# Eval("PictureName") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Image">
                                    <ItemTemplate>
                                        <asp:Image ID="Imagepath" runat="server" ImageUrl='<%# Eval("ProfilePicture") %>' Height="80px" Width="100px" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <EditRowStyle BackColor="#2461BF" />
                            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                            <RowStyle BackColor="#EFF3FB" />
                            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                            <SortedAscendingCellStyle BackColor="#F5F7FB" />
                            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                            <SortedDescendingCellStyle BackColor="#E9EBEF" />
                            <SortedDescendingHeaderStyle BackColor="#4870BE" />
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

Code Behind

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GridView : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=ADEQUATE-ASHOK\\SQLEXPRESS01;Initial Catalog=DemoDataBase;User ID=adk;Password=adk@1234");
        protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindDatagridview();
        }

    }

        protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            {
        string name = txtname.Text;
        string city = txtcity.Text;
        string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
        byte[] bytes;
        using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
                {
                    bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength);
                }
        string query = "insert into Students values (@Name,@City,@ProfilePicture,@PictureName)";
        using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Name", name);
                    cmd.Parameters.AddWithValue("@City", city);
                    cmd.Parameters.AddWithValue("@ProfilePicture", bytes);
                    cmd.Parameters.AddWithValue("@PictureName", FileUpload1.FileName);
                    con.Open();
        int i = cmd.ExecuteNonQuery();
                    con.Close();
        if (i > 0)
                    {
                        BindDatagridview();
                    }
        else
                    {
                        BindDatagridview();
                    }
                }


            }
        }
    }

        public void BindDatagridview()
    {
        SqlCommand cmd = new SqlCommand("select * from Students", con);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            DataRowView dr = (DataRowView)e.Row.DataItem;
        //conveting image to base64
        string imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["ProfilePicture"]);
            (e.Row.FindControl("Imagepath") as Image).ImageUrl = imageUrl;
        }
    }
}

As you can see in the above code on the GridView1_RowDataBound event we converting the Image Byte[] into Base64 for showing the image.

  • Page_Load: This method is called when the page is loaded. It checks if the page is loaded for the first time and then calls the BindDatagridview method to bind data to the GridView.
  • Button1_Click: This method handles the click event of the button used for uploading images. It retrieves the name, city, and uploaded file, converts the file to a byte array, inserts the data into the database, and then calls BindDatagridview to refresh the GridView.
  • BindDatagridview: This method retrieves data from the database and binds it to the GridView.
  • GridView1_RowDataBound: This event is raised for each row in the GridView. It retrieves the binary image data from the database, converts it to a Base64 string, and sets it as the ImageUrl for the Image control in the GridView.

Download Source Code

How to display binary images into a gridview in using Handler?

We can also use a handler to display images in gridview. Gridview ItemTemplate set image control ImageUrl as src=~/PictureHandler.ashx?Id=” + Id where PictureHandler.ashx is your handler name which return MemoryStream((byte[])img) and we can display it in our application;

Aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table class="auto-style1">
                <tr>
                    <td colspan="2">
                        <fieldset>
                            <legend>Add Students</legend>
                            <asp:TextBox ID="txtname" runat="server" placeholder="Name"></asp:TextBox>
                            <br />
                            <br />
                            <asp:TextBox ID="txtcity" runat="server" placeholder="City"></asp:TextBox>
                            <br />
                            <br />
                            <asp:FileUpload ID="FileUpload1" runat="server" />
                            <br />
                            <br />
                            <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
                        </fieldset>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:GridView ID="GridView1" runat="server" DataKeyNames="Id" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" Width="600px"  GridLines="None" Height="200px">
                            <AlternatingRowStyle BackColor="White" />
                            <Columns>
                                <asp:TemplateField HeaderText="Name">
                                    <ItemTemplate>
                                        <asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="City">
                                    <ItemTemplate>
                                        <asp:Label ID="lblCity" runat="server" Text='<%# Eval("City") %>'></asp:Label>
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Image Name">
                                    <ItemTemplate>
                                        <asp:Image ID="Imagepath" runat="server" ImageUrl='<%# "PictureHandler.ashx?Id="+ Eval("Id") %>' Height="80px" Width="100px" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                                <asp:TemplateField HeaderText="Image">
                                    <ItemTemplate>
                                        <asp:Image ID="Imagepath" runat="server" ImageUrl='<%# Eval("ProfilePicture") %>' Height="80px" Width="100px" />
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                            <EditRowStyle BackColor="#2461BF" />
                            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
                            <RowStyle BackColor="#EFF3FB" />
                            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
                            <SortedAscendingCellStyle BackColor="#F5F7FB" />
                            <SortedAscendingHeaderStyle BackColor="#6D95E1" />
                            <SortedDescendingCellStyle BackColor="#E9EBEF" />
                            <SortedDescendingHeaderStyle BackColor="#4870BE" />
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>

In the above GridView template field code on the page, we are displaying images using a handler file called PictureHandler.ashx.

An HTTP handler is a crucial component in handling requests and responses within an ASP.NET application. It processes incoming requests and generates appropriate responses, making it a fundamental part of ASP.NET request processing.

To add an HTTP handler to our project, follow these steps:

1. Right-click on your project.

2. Select "Add" and then "New Item."

3. Choose "Handler" from the list of available items.

4. Name your handler file as desired and click "Add."

Hanlder Code:

ProcessRequest(HttpContext context):
  • This method is invoked when a request is made to the handler. It processes the request and generates a response.
  • It retrieves the "Id" parameter from the query string of the request.
  • It establishes a connection to the database using the provided connection string.
  • Executes a SQL command to retrieve the profile picture data from the Students table based on the provided Id.
  • Reads the binary data representing the image from the SqlDataReader.
  • Writes the binary image data to the HTTP response using context.Response.BinaryWrite().
  • Closes the database connection and ends the response.
IsReusable Property:
  • This property indicates whether the handler can be reused for multiple requests.
  • In this case, it returns false, indicating that the handler instance should not be reused.
<%@ WebHandler Language="C#" Class="PictureHandler" %>

using System;
using System.Web;
using System.Data.SqlClient;
public class PictureHandler : IHttpHandler
{

        public void ProcessRequest(HttpContext context)
    {
        string Id = context.Request.QueryString["Id"];
        SqlConnection con = new SqlConnection("Data Source=ADEQUATE-ASHOK\\SQLEXPRESS01;Initial Catalog=DemoDataBase;User ID=adk;Password=adk@1234");
        con.Open();
        SqlCommand cmd = new SqlCommand("select ProfilePicture from Students where Id=" + Id, con);
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        context.Response.BinaryWrite((byte[])dr[0]);
        con.Close();
        context.Response.End();
    }

        public bool IsReusable
    {
        get
        {
        return false;
        }
    }

}

Aspx Code Behind Code:

Page_Load Method:
  • This method is executed when the page is loaded.
  • It checks if the page is being loaded for the first time (not a postback).
  • If it's not a postback, it calls the BindDatagridview method to populate the GridView with data.
Button1_Click Method:
  • This method is executed when Button1 is clicked.
  • It checks if a file has been uploaded using the FileUpload1 control.
  • If a file is uploaded, it reads the name and city input values.
  • It extracts the file name from the uploaded file.
  • It reads the binary data of the uploaded file using a BinaryReader.
  • It constructs an SQL query to insert the data into the Students table, including the name, city, profile picture binary data, and picture name.
  • The SqlCommand object is used to execute the SQL query after adding parameters.
  • After executing the query, it checks if any rows are affected. If so, it calls the BindDatagridview method to refresh the GridView with the updated data.
BindDatagridview Method:

  • This method retrieves data from the Students table in the database and binds it to the GridView.
  • It creates a new SqlCommand object to select all records from the Students table.
  • A SqlDataAdapter is used to fill a DataSet with the data retrieved from the database.
  • If the DataSet contains any rows, the data is bound to the GridView control.
Overall, below code allows users to upload data including a profile picture to the Students table in the database, and it displays the uploaded data in a GridView on the web page.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class GridView : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("Data Source=ADEQUATE-ASHOK\\SQLEXPRESS01;Initial Catalog=DemoDataBase;User ID=adk;Password=adk@1234");
    protected void Page_Load(object sender, EventArgs e)
    {
    if(!IsPostBack)
        {
            BindDatagridview();
        }

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
    if (FileUpload1.HasFile)
        {
            {
    string name = txtname.Text;
    string city = txtcity.Text;
    string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
    byte[] bytes;
    using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
                {
                    bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength);
                }
    string query = "insert into Students values (@Name,@City,@ProfilePicture,@PictureName)";
    using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    cmd.Parameters.AddWithValue("@Name", name);
                    cmd.Parameters.AddWithValue("@City", city);
                    cmd.Parameters.AddWithValue("@ProfilePicture", bytes);
                    cmd.Parameters.AddWithValue("@PictureName", FileUpload1.FileName);
                    con.Open();
    int i = cmd.ExecuteNonQuery();
                    con.Close();
    if (i > 0)
                    {
                        BindDatagridview();
                    }
    else
                    {
                        BindDatagridview();
                    }
                }


            }
        }
    }

    public void BindDatagridview()
    {
        SqlCommand cmd = new SqlCommand("select * from Students", con);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adp.Fill(ds);
    if (ds.Tables[0].Rows.Count > 0)
        {
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }
    }
}

DownLoad Source Code