Thursday, December 31, 2009

Display Images in GridView from Sql Server Database Table Using Asp.net C#




Please visit my new Web Site WWW.Codedisplay.com



In my previous post i showed you "How one can upload images into Sql Server using Asp.net C# FileUpload control". In this post i will show you how one can display images into a GridView from Sql Server table. As you know in most of the web applications requires to handle different type of images like large,thumbnail etc. If those web applications are e-commerce site then you must be carefull when handling images. In previous post i showed how you can store images & in this post i will show you how one can display images from Sql server table. The table structure is given below:




















Fig: Table structure

Displaying picture or image in a GridView is a different way then just using a image tag. In ASP.NET we can define a Handler to access the image from data base. So now we need to create a Handler to read binary data from database. To do that Right click on solution explorer and Add new item, click on Generic Handler and name it ImageHandler.ashx. Write this code in ProcessRequest method:
using System;
using System.Web;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public class ImageHandler : IHttpHandler 
{
    
    public void ProcessRequest (HttpContext context) 
    {
        string connectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select [Content] from Images where ID =@ID";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = conn;

        SqlParameter ImageID = new SqlParameter("@ID", SqlDbType.BigInt);
        ImageID.Value = context.Request.QueryString["ID"];
        cmd.Parameters.Add(ImageID);
        conn.Open();
        SqlDataReader dReader = cmd.ExecuteReader();
        dReader.Read();
        context.Response.BinaryWrite((byte[])dReader["Content"]);
        dReader.Close();
        conn.Close();
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}
Ok now add an aspx page in your project. Add a GridView control with a template field. Within the template field define image URL like below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Display_images.aspx.cs" Inherits="Display_images" %>

<!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>Display Images in GridView from SQL Server</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:GridView ID="GVImages" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="red" HeaderStyle-ForeColor="white">
        <Columns>
    
        <asp:BoundField DataField="ID" HeaderText="ID" />
        <asp:BoundField DataField="Name" HeaderText="Description" />
        <asp:BoundField DataField="Type" HeaderText="Type" />
    
        <asp:TemplateField HeaderText="Image">
        <ItemTemplate>
        <asp:Image ID="Image1" runat="server" 
                   ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'/>
        </ItemTemplate>
        </asp:TemplateField>
    
        </Columns>        
        </asp:GridView>
    
    </div>
    </form>
</body>
</html>
Now everything is set except binding sql server data into the GridView. To do that write the below code in Page_Load event:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;

public partial class Display_images : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(connectionString);
            using (conn)
            {
                SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Images", conn);
                ad.Fill(dt);
            }
            GVImages.DataSource = dt;
            GVImages.DataBind();
        }
    }
}
Now run the project & hope you wil get a webpage like below:















Fig: Sample Output

So i think now you can display images from sql server table into a GridView. Happy programming.

2 comments:

Salman ansari said...

thax a lot...can u do this think with the jquery..because i hav a .net web service and in place of aspx page i want to use simple html page..plz..thax

SHYAM SHARMA said...

Thanks.. your code helped me alot.. i was missing image handler in my code...
thanks again

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash