In this article I will explain with an example, how to display Images from SQL Server database stored in Binary format in ASP.Net GridView control using C# and VB.Net.
Image files will be uploaded and then will be saved (inserted) to SQL Server database table in Binary format. The saved (inserted) Image files will be retrieved and displayed in ASP.Net GridView along with feature to Zoom the Image using jQuery.
 
 

Database

This article makes use of a table named tblFiles whose schema is defined as follows.
Display images from SQL Server Database in ASP.Net GridView control
 
Note: You can download the database table SQL by clicking the download link below.
            Download SQL file
 
 

HTML Markup

The following HTML Markup consists of:
FileUpload – For selecting image file.
Button – For uploading image file to SQL Server database.
GridView - For displaying images from database.

Columns

GridView consists of a TemplateField column and two BoundField columns.
TemplateField consists of Image Control for displaying uploaded image file.
 

Events

OnRowDataBound – For getting control of each GridView Row.
<asp:FileUpload ID="fuUpload" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
<hr />
<asp:GridView ID="gvImages" runat="server" AutoGenerateColumns="false" OnRowDataBound="OnRowDataBound">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Image Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
        <asp:TemplateField HeaderText="Image">
            <ItemTemplate>
                <asp:Image ID="Image1" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
<div id="dialog" style="display:none">
</div>
 
 

Namespaces

You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
 
VB.Net
Imports System.IO
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
 
 

Displaying Binary Images from database in ASP.Net GridView

Inside the Page Load event handler, the GridView is populated with records from the tblFiles table of SQL Server database.
Inside the OnRowDataBound event handler of the GridView, the Binary data i.e. BYTE Array is converted into a BASE64 string and assigned to the ImageUrl property of the Image control inside the GridView.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblFiles", conn))
            {
                DataTable dt = new DataTable();
                sda.Fill(dt);
                gvImages.DataSource = dt;
                gvImages.DataBind();
            }
        }
    }
}
 
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView dr = (DataRowView)e.Row.DataItem;
        string imageUrl "data:image/jpg;base64," + Convert.ToBase64String((byte[])dr["Data"]);
        (e.Row.FindControl("Image1")as Image).ImageUrl = imageUrl;
    }
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Using conn As SqlConnection = New SqlConnection(constr)
            Using sda As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM tblFiles", conn)
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)
                gvImages.DataSource = dt
                gvImages.DataBind()
            End Using
        End Using
    End If
End Sub
 
Protected Sub OnRowDataBound(ByVal sender As ObjectByVal e As GridViewRowEventArgs)
    If e.Row.RowType DataControlRowType.DataRowThen
        Dim dr As DataRowView = CType(e.Row.DataItem,DataRowView)
        Dim imageUrl As String "data:image/jpg;base64," & Convert.ToBase64String(CType(dr("Data"), Byte()))
        CType(e.Row.FindControl("Image1"), Image).ImageUrl = imageUrl
    End If
End Sub
 
 

Uploading and saving Image in Binary format in SQL Server database in ASP.Net

The following event handler gets called when an Image file is selected and the Upload Button is clicked.
The uploaded Image file is converted to an Array of Bytes using BinaryReader class and is finally inserted into the SQL Server database table.
C#
protected void Upload(object sender, EventArgs e)
{
    byte[] bytes;
    using (BinaryReader br = new BinaryReader(fuUpload.PostedFile.InputStream))
    {
         bytes = br.ReadBytes(fuUpload.PostedFile.ContentLength);
    }
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string sql = "INSERT INTO tblFilesVALUES(@Name, @ContentType, @Data)";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.AddWithValue("@Name", Path.GetFileName(fuUpload.PostedFile.FileName));
            cmd.Parameters.AddWithValue("@ContentType", fuUpload.PostedFile.ContentType);
            cmd.Parameters.AddWithValue("@Data", bytes);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
 
    Response.Redirect(Request.Url.AbsoluteUri);
}
 
VB.Net
Protected Sub Upload(ByVal sender As ObjectByVal e As EventArgs)
    Dim  bytes As Byte()
    Using br As BinaryReader = New BinaryReader(fuUpload.PostedFile.InputStream)
         bytes = br.ReadBytes(fuUpload.PostedFile.ContentLength)
    End Using
 
    Dim constr As String ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using conn As SqlConnection = New SqlConnection(constr)
        Dim sql As String "INSERT INTO tblFilesVALUES(@Name, @ContentType, @Data)"
        Using  cmd As SqlCommand = New SqlCommand(sql, conn)
            cmd.Parameters.AddWithValue("@Name", Path.GetFileName(fuUpload.PostedFile.FileName))
            cmd.Parameters.AddWithValue("@ContentType", fuUpload.PostedFile.ContentType)
            cmd.Parameters.AddWithValue("@Data", bytes)
            conn.Open()
            cmd.ExecuteNonQuery()
            conn.Close()
        End Using
    End Using
 
    Response.Redirect(Request.Url.AbsoluteUri)
End Sub
 
 

Implement Zoom feature when Image is clicked using jQuery

A jQuery click event handler is assigned to all the Image controls within the GridView.
When an HTML Image element is clicked, the Image controls is cloned and displayed in larger size within a jQuery UI Model Popup.
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.13.2/jquery-ui.js"></script>
<script type="text/javascript">
    $(function () {
        $("#dialog").dialog({
            autoOpen: false,
            modal: true,
            height: 250,
            width: 250,
            title: "Zoomed Image"
        });
        $("[id*=gvImages] img").click(function () {
            $('#dialog').html('');
            $('#dialog').append($(this).clone());
            $('#dialog').dialog('open');
        });
    });
</script>
 
 

Screenshot

Display images from SQL Server Database in ASP.Net GridView control
 
 

Downloads