Hi
try this example to Insert and Display Image from Database in Gridview
Database Script:
CREATE DATABASE [Employee]
GO
USE [Employee]
GO
CREATE TABLE EmpDetails
(
empid int IDENTITY NOT NULL,
empname varchar(20),
empimg image
)
Default.aspx
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”Default.aspx.cs” Inherits=”_Default” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd“>
<html xmlns=”http://www.w3.org/1999/xhtml“>
<head runat=”server”>
<title>Save Retrieve Images</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<asp:Label ID=”lblEmpName” runat=”server” Text=”Employee Name”></asp:Label>
<asp:TextBox ID=”txtEName” runat=”server”></asp:TextBox>
<br />
<asp:Label ID=”lblImage” runat=”server” Text=”Employee Image”></asp:Label>
<asp:FileUpload ID=”imgUpload” runat=”server” />
<br />
<br />
<asp:Button ID=”btnSubmit” runat=”server” onclick=”btnSubmit_Click”
Text=”Submit” />
<asp:Label ID=”lblResult” runat=”server” ForeColor=”#0066FF”></asp:Label>
<br />
<hr />
<asp:Image ID=”Image1″ style=”width:200px” Runat=”server” />
</div>
</form>
</body>
</html>
Default.asp.cs
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection connection = null;
try
{
FileUpload img = (FileUpload)imgUpload;
Byte[] imgByte = null;
if (img.HasFile && img.PostedFile != null)
{
//To create a PostedFile
HttpPostedFile File = imgUpload.PostedFile;
//Create byte Array with file len
imgByte = new Byte[File.ContentLength];
//force the control to load data in array
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
// Insert the employee name and image into db
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
connection = new SqlConnection(conn);
connection.Open();
string sql = “INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY”;
SqlCommand cmd = new SqlCommand(sql, connection);
cmd.Parameters.AddWithValue(“@enm”, txtEName.Text.Trim());
cmd.Parameters.AddWithValue(“@eimg”, imgByte);
int id = Convert.ToInt32(cmd.ExecuteScalar());
lblResult.Text = String.Format(“Employee ID is {0}”, id);
// Display the image from the database
Image1.ImageUrl = “~/ShowImage.ashx?id=” + id;
}
catch
{
lblResult.Text = “There was an error”;
}
finally
{
connection.Close();
}
}
}
In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > ShowImage.ashx. Add the code shown below to the handler.
ShowImage.ashx
<%@ WebHandler Language=”C#” Class=”ShowImage” %>
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException(“No parameter specified”);
context.Response.ContentType = “image/jpeg”;
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}
public Stream ShowEmpImage(int empno)
{
string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = “SELECT empimg FROM EmpDetails WHERE empid = @ID”;
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(“@ID”, empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
ViewImage.aspx
<asp:GridView ID=”GridView1″ runat=”server” AllowPaging=”True” AutoGenerateColumns=”False”
CellPadding=”4″ DataKeyNames=”empid” DataSourceID=”SqlDataSource1″ ForeColor=”#333333″>
<FooterStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<Columns>
<asp:BoundField DataField=”empid” HeaderText=”Id” InsertVisible=”False” ReadOnly=”True”
SortExpression=”empid” />
<asp:BoundField DataField=”empname” HeaderText=”Employee Name” SortExpression=”empname” />
<asp:TemplateField HeaderText=”Employee Image” SortExpression=”empimg”>
<ItemTemplate>
<asp:Image ID=”Image1″ runat=”server” Height=”107px” ImageUrl=’<%# Eval(“empid”, “~/ShowImage.ashx?id={0}”) %>’
Width=”108px” />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle BackColor=”#EFF3FB” />
<EditRowStyle BackColor=”#2461BF” />
<SelectedRowStyle BackColor=”#D1DDF1″ Font-Bold=”True” ForeColor=”#333333″ />
<PagerStyle BackColor=”#2461BF” ForeColor=”White” HorizontalAlign=”Center” />
<HeaderStyle BackColor=”#507CD1″ Font-Bold=”True” ForeColor=”White” />
<AlternatingRowStyle BackColor=”White” />
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:EmployeeConnString %>”
ProviderName=”<%$ ConnectionStrings:EmployeeConnString.ProviderName %>” SelectCommand=”SELECT * FROM [EmpDetails]“>
</asp:SqlDataSource>
Hope it helps
Good Luck