How to Display Binary Image in Gridview from Database in Asp .Net c#

How to Display Binary Image in Gridview from Database in Asp .Net c#

As we know that GridView control is a feature-rich control for displaying and editing data on a Web Application. It is a very popular commonly used control in ASP.Net for manipulating data.In this post, we will learn how we can display binary images into a Gridview.

I google for that and I found many ways to complete this task but many developers suggested using a handler or converting image to Base64 Image. So I decided to write both approaches in this article and end of the post you can also download the source code.

So we take a Fileupload and a button in the Webforms and a GridView for displaying the images. On Click on the Upload button, we will upload the image files into the database in Binary format, and then we will be retrieved and displayed the uploaded images in 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.

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>

 

You can see in the above gridview TemplateField code on the page we are showing images using Handler file PictureHandler.ashx.

What is HTTP handler: Every request into our web application is handled by an HTTP handler. The HTTP handler is the most important component while handling ASP.NET requests and responses.

To let’s add HTTPHandler in our Project file

  • Right Click on your project Add New Item > select Handler

Hanlder Code:

<%@ 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:

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

Ashok Patel

I'm an electronic engineer working in a multinational company,having good experience on Electronics and electrical engineers design and oversee production of electronic equipment such as radios, televisions, computers, washing machines and telecommunication systems.I like to do RND and Research.I also have hands on experience graphic design software and in web designing having great command on ASP.NET, HTML5, JavaScript, T-SQL, JQuery.

Add comment

Your Header Sidebar area is currently empty. Hurry up and add some widgets.