Wednesday, 9 April 2014

How to Display Image in Gridview from Database

Display image in gridview 

In this article we will see how to display image in a gridview  from database (SQL Server).
In this case we need a Template column in a gridview and add html image (img) tag in it. you can also take asp.net image control but it will generate view state so we have taken html img tag.
if you are using asp.net image control than i would suggest that make the EnableViewState property of image control to false.
Lets see the scenario

Display Picture in a GridView from Database

let's 1st create a table and call it as Image_Table to create sample table below is the code. Here I am using Image data type of SQL server to save image into it. As we all know that SQL Server store Image as binary data in a column of datatype IMAGE.


CREATE TABLE [dbo].[Image_Table](

 [id] [int] IDENTITY(1,1) NOT NULL,

 [SomeText] [varchar](50) NULL,

 [ImagePath] [varchar](200) NULL,

 [Image_Blob] [image] NULL,

 CONSTRAINT [PK_Image_Table] 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] 

Here is the table schema in figure


 Now Create one stored procedure to fetch data from database and bind that to GridView

CREATE PROCEDURE GetImageInfoFromDB

AS

BEGIN
 SELECT  id,SomeText,ImagePath,Image_Blob FROM dbo.Image_Table

END
In this example we are using HTTPHandler to fetch Images from Database. For that I have created another stored procedure which will accept one input parameter id


CREATE PROCEDURE GetImageFromDB(@id int)

AS

BEGIN        
 SELECT  id,SomeText,ImagePath,Image_Blob FROM dbo.Image_Table WHERE id = @id

END

I assume that some data is available into the table    


  To add HTTPHandler right click on the project explorer --> AddNewItem --> Generic Handler from the templete eg given pic below and Name it as ImageHanlder.ashx
 

Now in you HTTPHandler you can add this lines of code

<%@ WebHandler Language="C#" Class="ImageHandler" %>

 

using System;

using System.Web;

using System.Data.SqlClient;

using System.Data;

using System.Configuration;

 
 

public class ImageHandler : IHttpHandler {

 

    public void ProcessRequest(HttpContext context)

    {

        string strId = context.Request.QueryString["Id"];

 

        if (!string.IsNullOrEmpty(strId))

        {

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

            SqlDataReader sqlDr = null;

            try

            {

                conn.Open(); //open database connection

 

                SqlCommand sqlCmd = new SqlCommand("GetImageFromDB", conn);

                sqlCmd.CommandType = CommandType.StoredProcedure;

                 

                //Add the parameter to SQLCommand object

                sqlCmd.Parameters.AddWithValue("@id", strId);

 

                sqlDr = sqlCmd.ExecuteReader();

 

                sqlDr.Read();

 

                context.Response.BinaryWrite((Byte[])sqlDr[3]);

 

                context.Response.End();

                 

                 

            }

            catch (Exception ex)

            {

                //Handle error If occured

            }

            finally

            {

                if (sqlDr != null && !sqlDr.IsClosed)

                {

                    sqlDr.Close(); //close SqlDataReader

                }

                conn.Close();//close database connection

            }

        }

 

    }

  

    public bool IsReusable {

        get {

            return false;

        }

    }

 

}

Now in you page in which gridView is there your code should look like this after adding templete column

<asp:gridview id="GridView1" runat="server" autogeneratecolumns="False">

       <columns>

           <asp:boundfield datafield="SomeText" headertext="Header Text">

           <asp:templatefield headertext="Image Form DataBase">

               <itemtemplate>

                   <img alt="Image" src="%3C%#%20%22ImageHandler.ashx?Id=%22+%20Eval%28%22id%22%29%20%%3E" height="70px" width="70px">

               </itemtemplate>

           </asp:templatefield>

       </asp:boundfield></columns>

   </asp:gridview> 

Now to bind data in a gridview you can add below lines of code in any event in which you want like Page Load event, Button Click event etc.
In C# example


private void LoadData()

{

 

        string returnValue = string.Empty;

 

        //Get the databse connection string from web.config file

        string conString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

 

        SqlConnection sqlConn = new SqlConnection(conString);

        SqlDataReader sqlDr = null;

        try

        {

            //Call the stored procedure using SQLDataAdapter

            SqlDataAdapter salDa = new SqlDataAdapter("GetImageInfoFromDB", sqlConn);

             

            DataSet ds = new DataSet();

            salDa.Fill(ds);   // Fill the dataset

 

            //Bind the data which in form of dataset to ggridview

            GridView1.DataSource = ds;

            GridView1.DataBind();

 

        }

        catch (Exception ex)

        {

            //Handle Error if any occured

        }

        finally

       {

            if (sqlDr != null && !sqlDr.IsClosed)

            {

                sqlDr.Close(); //close sqldatareader

            }

            //Close SQL connection

            sqlConn.Close();

        }

 
} 







































 If you run the application you can see in image in gridview like this










































































































































































































1 comment:

  1. dịch vụ nhận vận chuyển hàng trung quốc về việt nam nhanh chóng, uy tín, giá rẻ. công ty vận chuyển hàng hóa trung quốc chuyên nghiệp, đã và đang được nhiều người tiêu dùng trong nước sử dụng. Chuyên nhận nhận ship hàng từ trung quốcorder hàng trung quốc về Việt Nam với chí phí thấp nhất, giá cạnh tranh cao. Ngoài ra, chúng tôi còn cung cấp dịch vụ mua mua hàng trung quốc giá sỉ với nhiều ưu đãi và tiện ích.
    Không chỉ các mặt hàng trung quốc, chúng tôi còn nhận order hàng nhật. Để xem chi tiết khoản giá cạnh tranh ở chúng tôi, xem chi tiết tại phí chuyển hàng từ nhật về việt nam. hơn nữa, quý khách có thể vận chuyển hàng từ nhật về việt namgửi đồ từ nhật bản về việt nam những những món đồ cồng kềnh, khó vận chuyển. Với dịch vụ chuyên nghiệp của chúng tôi ,chắc chắn sẽ đem lại nhiều sự hài lòng cho quý khách.

    ReplyDelete