Monday 27 February 2012

How can we display images in datalist using asp.net

I am using DataList control  but you can easily use same technique for Repeater and GridView control. 
 
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal"
   Width="100%" BorderColor="#336699" BorderStyle="Solid" BorderWidth="2px">
  
   <ItemTemplate>
      <asp:Label ID="Label1" runat="server" Text='<%# Eval("ProductName") %>' Font-Bold="True"
         Font-Size="10pt" ForeColor="#336699" Width="100%" />
      <br />
      <asp:Image ID="Image1" runat="server"
         ImageUrl='<%# "GetImage.aspx?id=" + Eval("ProductID") %>' />

   </ItemTemplate>
   <ItemStyle HorizontalAlign="Center" VerticalAlign="Top"  />
</asp:DataList>




It is using ItemTemplate of DataList control to display Product Name and Product Image. The interesting line for you is the Image control that has ImageUrl property set to another asp.net page which will actually generate images from the database.

You need to bind the above DataList control by using the code shown below. The code is simple ADO.NET code in which I fill one DataTable object and bind DataList control with the data table.

if (!Page.IsPostBack)
{
   string constr = "Server=SampleServer; Database=SampleDB; uid=test; pwd=test";
   string query = "SELECT ProductID, ProductName FROM Products";

   SqlDataAdapter da = new SqlDataAdapter(query, constr);
   DataTable table = new DataTable();

   da.Fill(table);
   DataList1.DataSource = table;
   DataList1.DataBind();
}

Now we are moving to interesting part of this jigsaw puzzle, GetImage.aspx page. As I already told you that GetImage.aspx page main job is to read your binary image from the database and render it on the Image control. I am passing the Product ID to this page as query string as you have seen above in the Image control in the DataList ItemTemplate.
protected void Page_Load(object sender, EventArgs e)
{
   string id = Request.QueryString["id"];

   string constr = "Server=SampleServer; Database=SampleDB; uid=test; pwd=test";
   string query = "SELECT ProductImage FROM Products WHERE ProductID = @ProductID";

  SqlConnection con = new SqlConnection(constr);
  SqlCommand com = new SqlCommand(query, con);

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

  con.Open();
  SqlDataReader r = com.ExecuteReader();
 
  if (r.Read())
  {
     byte[] imgData = (byte[])r["ProductImage"];
     Response.BinaryWrite(imgData);

  }
  con.Close();
}

No comments:

Post a Comment