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
The post How to Display Binary Image in Gridview from Database in Asp .Net c# appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- Simple Way Find and replace text in Word document using C#
- Implementing “Remember Me” Feature in ASP.NET MVC
- [Solved]-Cookie loses value when page is changed in MVC
- How to post File Upload and other form fields to one action Asp .Net MVC C#
- How To Post File and Data to API using HttpClient C#
- Create ASP.NET Core Web API Without Entity Framework
- .NET Core Web API Using Code First Entity Framework Approach
- Create Asp.Net Core Web Api Using Entity Framework Database First
- Registration form with image upload in MVC using jquery Ajax
- How to make an Inline editable table in MVC using jquery?
- CRUD operation using partial view in MVC with modal popup
- Insert Update Delete Using Jquery Ajax and Modal Popup in Mvc
- Crud Operations in MVC Without Entity Framework
- Create Login,Signout and Registration in Asp .Net Mvc Using Entity
- Export Gridview to Excel and Csv in Asp .Net With Formatting Using c#
- How to Display Binary Image in Gridview from Database in Asp .Net c#
- [Solved]-How to Upload pdf file using jquery MVC?
- [Solved]-Uploading both data and files in FormData using Ajax MVC
- C# -Saving a base64 string as an image into a folder on server in Web Api
- [Solved]-Download pdf file from link and save in local file folder in Asp .Net
- [Solved]-Delete Files older than X Months,Days,Minute in a Directory- C# .NET
- [Solved]-LEFT OUTER JOIN in LINQ With Where clause in C#
- INNER JOIN,RIGHT JOIN,LEFT JOIN USING LINQ IN Multiple Table C#
- [Solved]-Convert Base64 To Image And Save in folder and Display it- C#
- [Solved]-How to Overlay Two Images in .NET-C#
- How to Create Multilingual Website in Asp .Net
- C# – How to add double quotes to a string that is inside a variable
- Update an Image with Upload Button For Each Row in Gridview-Asp .Net
- How to Bind Data in DataList Control in Asp.Net – C#
- Upload and Display an Image in Gridview From Image Path in Database -C#