In this article I will explain with an example, how to display Binary Image from SQL Server database in ASP.Net GridView control using C# and VB.Net.
Image files will be uploaded and then will be saved (inserted) to 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 Binary Image from database in ASP.Net GridView control using C# and VB.Net
 
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 an ASP.Net FileUpload control, Button, a GridView and an HTML DIV.
<asp:FileUpload ID="FileUpload1" 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 records from the database table are fetched and are used to populate the GridView control.
Inside the RowDataBound event 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 Object, ByVal 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 Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        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 finally is inserted into the database table.
C#
protected void Upload(object sender, EventArgs e)
{
    byte[] bytes;
    using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))
    {
        bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength);
    }
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string sql = "INSERT INTO tblFiles VALUES(@Name, @ContentType, @Data)";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.AddWithValue("@Name", Path.GetFileName(FileUpload1.PostedFile.FileName));
            cmd.Parameters.AddWithValue("@ContentType", FileUpload1.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 Object, ByVal e As EventArgs)
    Dim bytes As Byte()
    Using br As BinaryReader = New BinaryReader(FileUpload1.PostedFile.InputStream)
        bytes = br.ReadBytes(FileUpload1.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 tblFiles VALUES(@Name, @ContentType, @Data)"
        Using cmd As SqlCommand = New SqlCommand(sql, conn)
            cmd.Parameters.AddWithValue("@Name", Path.GetFileName(FileUpload1.PostedFile.FileName))
            cmd.Parameters.AddWithValue("@ContentType", FileUpload1.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 HTML Image elements within the GridView. When an HTML Image element is clicked, the Image element is cloned and displayed in larger size within a jQuery UI Model Popup.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/themes/start/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#dialog").dialog({
            autoOpen: false,
            modal: true,
            height: 600,
            width: 600,
            title: "Zoomed Image"
        });
        $("[id*=gvImages] img").click(function () {
            $('#dialog').html('');
            $('#dialog').append($(this).clone());
            $('#dialog').dialog('open');
        });
    });
</script>
 
 
Screenshot
Display Binary Image from database in ASP.Net GridView control using C# and VB.Net
 
 
Downloads