In this article I will explain with an example, how to use Generic HTTP Handler to display Binary Images from database in ASP.Net using C# and VB.Net.
The Binary Image will be fetched from database and then displayed in Image control with the help of Generic HTTP Handler in ASP.Net using C# and VB.Net.
Binary Images stored in Database
The following screenshot displays database table with three images stored in it. The backup file of the database is present in the attached sample.
HTML Markup
The HTML Markup consists of a DropDownList control which will populate the list of image files in database and an Image control to display the selected image.
The DropDownList control has been assigned with SelectedIndexChanged event handler.
<asp:DropDownList ID="ddlImages" runat="server" AppendDataBoundItems="true" AutoPostBack = "true" OnSelectedIndexChanged = "FetchImage">
<asp:ListItem Text="Select Image" Value="0" />
</asp:DropDownList>
<hr />
<asp:Image ID="Image1" runat="server" Visible = "false"/>
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Populating the List of Images in DropDownList control
Inside the Page Load event, the Images are fetched from database and are assigned to the DropDownList control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter("SELECT Id, Name FROM tblFiles", con))
{
sda.Fill(dt);
ddlImages.DataSource = dt;
ddlImages.DataTextField = "Name";
ddlImages.DataValueField = "Id";
ddlImages.DataBind();
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As DataTable = New DataTable()
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(constr)
Using sda As SqlDataAdapter = New SqlDataAdapter("SELECT Id, Name FROM tblFiles", con)
sda.Fill(dt)
ddlImages.DataSource = dt
ddlImages.DataTextField = "Name"
ddlImages.DataValueField = "Id"
ddlImages.DataBind()
End Using
End Using
End If
End Sub
The Generic Handler
The following Generic Handler accepts the ID of the Image file through the QueryString parameter and fetches the Binary Data of the Image file from the database using its ID.
Finally the Binary Data is converted into a Byte Array and returned through the response.
C#
<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
int id = 0;
int.TryParse(context.Request.QueryString["id"], out id);
if (id > 0)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string sql = "SELECT Data, ContentType FROM tblFiles WHERE Id =" + id;
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
DataTable dt = new DataTable();
sda.Fill(dt);
byte[] bytes = (byte[])dt.Rows[0]["Data"];
context.Response.ContentType = dt.Rows[0]["ContentType"].ToString();
context.Response.BinaryWrite(bytes);
context.Response.End();
}
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
VB.Net
<%@ WebHandler Language="VB" Class="Handler" %>
Imports System
Imports System.Web
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Public Class Handler : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim id As Integer = 0
Integer.TryParse(context.Request.QueryString("id"), id)
If (id > 0) Then
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim con As SqlConnection = New SqlConnection(constr)
Dim sql As String = ("SELECT Data, ContentType FROM tblFiles WHERE Id =" & id)
Dim sda As SqlDataAdapter = New SqlDataAdapter(sql, con)
Dim dt As DataTable = New DataTable
sda.Fill(dt)
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
context.Response.ContentType = dt.Rows(0)("ContentType").ToString
context.Response.BinaryWrite(bytes)
context.Response.End()
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
Displaying the Binary Image from database in Image Control using Generic Handler
The following event handler is executed on the SelectedIndexChanged event of the DropDownList control. The ID of the Image is appended in the URL of the Generic HTTP Handler and the URL is assigned to the Image control.
As soon as the Page is rendered, the Generic HTTP Handler is called and it returns the Image data i.e. Binary data to the Image control which ultimately displays the Image.
C#
protected void FetchImage(object sender, EventArgs e)
{
string id = ddlImages.SelectedItem.Value;
Image1.Visible = id != "0";
Image1.ImageUrl = string.Format("~/Handler.ashx?id={0}", id);
}
VB.Net
Protected Sub FetchImage(ByVal sender As Object, ByVal e As EventArgs)
Dim id As String = ddlImages.SelectedItem.Value
Image1.Visible = (id <> "0")
Image1.ImageUrl = String.Format("~/Handler.ashx?id={0}", id)
End Sub
Screenshot
Demo
Downloads