Introduction

Display an Image in Grid view

.Aspx Page

<asp:TemplateField HeaderText="Photo" ItemStyle-HorizontalAlign="Center">
<
ItemTemplate>

<
asp:Image Width="20px" Height="20px" ID="ImagePhoto" runat="server" ImageUrl='<%#"ImageHandler.ashx?Photoid=" + Eval("Photo_Image_id")%>' />
<%
#GeneratePhotoDetailLink(Eval("Photo_Image_id"),Eval("photo_image_ext"))%>
</
ItemTemplate>
</
asp:TemplateField>

.Aspx.cs Page

protected string GeneratePhotoDetailLink(object Photo_Image_id, object photo_image_ext)
{

// If there is no image, mentioned text will be displayed in the gridview.
if
(photo_image_ext == null)
{

return
"No File Available";
}

else

{

return
string.Format(@"<a target=""_blank"" href=ImageHandler.ashx?Photoid=" + Photo_Image_id.ToString() + ">" + "View" +
"</a>");
}

Image Handler

public void ProcessRequest(HttpContext context)
{
try

{
ListOfImages
objListOfImages = new ListOfImages();
List
<ListOfImages> lstListOfImages = new List<ListOfImages>();
Int32
? RecordId = 0;

context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

context.Response.BufferOutput = false;

//get the id from the query string.

if
(context.Request.QueryString["Record_Id"] != null)

{

RecordId = Int32.Parse(context.Request.QueryString["Record_Id"]);

}

//set the type to Image/jpeg, or png or gif, any type that you are returning.
context.Response.ContentType = "Image/jpeg";

//get the session object.

context.Session["sessionLOI"] = HttpContext.Current.Session["sessionListOfImages"];

if
(context.Session["sessionLOI"] != null)

{
lstListOfImages = (List<ListOfImages>)context.Session["sessionLOI"];
foreach
(var objLoI in lstListOfImages)
{
if (RecordId != null && RecordId != 0)
{
if
(RecordId == objLoI.Record_Id)

{

if
(objLoI.Image != null)

{

context.Response.BinaryWrite(objLoI.Image);

}

break
;
}
}

}

}

catch
(Exception ex)

{

context.Response.Write(ex.Message);

}

}

public
bool IsReusable

{

get

{

return
false;

}

}