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.
For that, I have created a Students table in SQL database which store in information from our Web Application.
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>
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.
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;
<%@ 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."
<%@ 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;
}
}
}
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();
}
}
}