Display Images in DataList Control from SQL Server Database in Asp.Net C# VB.Net

Some developers want to store Images into SQL Server Database. For those developers need to retrieve Images from Database and display those images either in GridView or DataList control. In my previous article I have explained how to display images from database into GridView. And in this article I am going to explain How one can display stored Images from SQL Server Database into Asp.Net DataList control. I am providing this example by developing a product display page using DataList.

Related Articles:
1. Save Images into Sql Server Database Table using Asp.Net FileUpload Control C# VB.Net
2. Display Images in GridView from Sql Server Database Table Using Asp.net C# VB.Net

Display Images in DataList Control from SQL Database in Asp.Net Csharp VB.Net

To do the example I am assuming that you have already a database table with some stored images like below:

HTML Code for the DataList Control:

<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal"
   Width="100%" BorderColor="Blue" BorderStyle="Solid" BorderWidth="3px">
      <asp:Label ID="Label1" runat="server" Text='<%# Eval("ProductName") %>' Font-Bold="True" Font-Size="1.2em" ForeColor="Navy"/><br />
      <asp:Label ID="Label2" runat="server" Text='<%# Eval("ProductDescription") %>' Font-Italic="true"/><br /> 
      <asp:Label ID="Label3" runat="server" Text='<%# "Price: US$"+System.Convert.ToString(Eval("ProductPrice")) %>' Font-Bold="True" Font-Size="1.2em" ForeColor="Navy"/><br />
      <asp:Image ID="Image1" runat="server" ImageUrl='<%# "GetImageDatafromDB.aspx?id=" + System.Convert.ToString(Eval("ProductID")) %>'/>
   <ItemStyle HorizontalAlign="Center" VerticalAlign="Top"  />

Note: If you look at the Image control ImageUrl properties which is pointed to another URL. Actually this GetImageDatafromDB.aspx page will generate the image.

Namespaces required for this example:
1. System.Data
2. System.Data.SqlClient
3. System.Configuration

Now first Bind the DataList Control from DataBase using ADO.Net:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!Page.IsPostBack)
            string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(connectionString);
            using (conn)
                SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Product", conn);
            DataList1.DataSource = dt;

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim connectionString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
            Dim dt As New DataTable()
            Dim conn As New SqlConnection(connectionString)
            Using conn
                Dim ad As New SqlDataAdapter("SELECT * FROM Product", conn)
            End Using
            DataList1.DataSource = dt
        End If
    End Sub

Now we need to work on GetImageDatafromDB.aspx page. As I already told you that GetImageDatafromDB.aspx page main job is to read your binary image from the database and display it on the Image control of the DataList. To get the corresponding image of a product here I am passing the Product ID to this page as query string as stated above in the Image control in the DataList ItemTemplate.

So now add the GetImageDatafromDB.aspx page & write below code under Page_Load Event:
C# Code:

    protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
            string sProductID = Request.QueryString["id"];

            string constr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            string sQuery = "SELECT ProductImage FROM Product WHERE ProductID = @ProductID";

            SqlConnection con = new SqlConnection(constr);
            SqlCommand cmd = new SqlCommand(sQuery, con);

            cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = Int32.Parse(sProductID);

            using (con)
                SqlDataReader DR = cmd.ExecuteReader();

                if (DR.Read())
                    byte[] imgData = (byte[])DR["ProductImage"];

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim sProductID As String = Request.QueryString("id")

            Dim constr As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
            Dim sQuery As String = "SELECT ProductImage FROM Product WHERE ProductID = @ProductID"

            Dim con As New SqlConnection(constr)
            Dim cmd As New SqlCommand(sQuery, con)

            cmd.Parameters.Add("@ProductID", SqlDbType.Int).Value = Int32.Parse(sProductID)

            Using con
                Dim DR As SqlDataReader = cmd.ExecuteReader()

                If DR.Read() Then
                    Dim imgData As Byte() = DirectCast(DR("ProductImage"), Byte())
                End If
            End Using
        End If
    End Sub

Note: Don’t forget to add above mentioned namespaces also for this page handler.

Hope now you can Bind SQL Server stored images into DataList Control.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, DataList, VB.Net
11 comments on “Display Images in DataList Control from SQL Server Database in Asp.Net C# VB.Net
  1. aarti says:

    hii u are using id =@id in where clause, but at the place of id =@id i want to use where name ='”+Label1.text+”‘ .. i am tring this code but its not working … i can just use only id not a label in where clause. can u help me.. i want to display binary image of particular person who is login

    • Shawpnendu Bikash says:

      Most probably you have wrongly configured the name parameter. Need your code for further help.

  2. Gokul says:

    Thanks a lot.It helped me a lot

  3. Sujata says:

    thanks.It is really helpful for me.But image on datalist only show cross mark instead of actual image.

  4. Kiran says:

    Image is not Displaying…. where to put image path….

    • code display says:

      Here i have explained to display images from SQL Server Database. Hence reading binary data only not path. If you need more clarification please let me know.

  5. Alan says:

    I dont have actual images in database instead i gave the url path what would be the code for that.

  6. Alan says:

    It would be real help if u can give the code Thanku.

  7. Jo says:

    Image display in the datalist is not done. what could be the reason??

  8. Feroz says:

    Fantastic and Simple way to load… but just wondering what if we use ASHX rather than ASPX ??? Anyway this code was simply a nice one. Thanks

  9. sai says:

    image not displaying

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code