This article describes how to display images which are stored in a database.
Step 1: Create page Default.aspx with following code
Here is the code on Default.aspx Page:
<asp:DataList ID="myList" runat="server">
<ItemTemplate>
<table>
<tr>
<td width="20%">
<asp:Image ID="Image1" runat="server" Width="150" Height="125"
ImageUrl='<%# DataBinder.Eval(Container.DataItem, "TestimonialID","ReadRealImage.aspx?ID={0}") %>'/>
</td>
<td>
<asp:Label ID="mylabel" runat="Server" text='<%#Eval("Testimonial") %>' />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Step 2: Code Behind will contain the code shown below
Here is the code on Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack != true)
{
LoadTestimonials();
}
}
private void LoadTestimonials()
{
dlTestimonials.DataSource = BAL_Testimonial.SelectAll();
dlTestimonials.DataBind();
}
Step 3: Create Page that will return Image as Output.
Here you also create httpHandler. Get the ID from Image that you want to return from QueryString[“ID”].
Here is the code on ReadRealImage.aspx:
protected void Page_Load(object sender, EventArgs e)
{
int TestimonialID = 0;
if (Request.QueryString["ID"].ToString() != null)
{
TestimonialID = Convert.ToInt32(Request.QueryString["ID"].ToString());
}
SQLHelper objSQLHelper = new SQLHelper();
System.Data.SqlClient.SqlConnection _SqlConn = objSQLHelper.SQLConn;
SqlCommand _SqlCommand = new SqlCommand("JobsDb_Testimonial_Select", _SqlConn);
_SqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
_SqlCommand.Parameters.Add(new System.Data.SqlClient.SqlParameter("@TestimonialID", TestimonialID));
_SqlConn.Open();
SqlDataReader reader = _SqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);
if (reader.HasRows)
{
while (reader.Read())
{
Response.ContentType = reader["PicType"].ToString();
Response.BinaryWrite((byte[])reader["Pic"]);
}
}
reader.Close();
}
Step 4: Procedure & Tables Details
Here i have given you the procedure that i have used in my example, you can user your table & procedure in which the Images are stored.
CREATE PROCEDURE [dbo].[Testimonial_Select]
@TestimonialID int
AS
BEGIN
SELECT PicType,Pic FROM [dbo].Testimonials WHERE TestimonialID = @TestimonialID
END
GO
CREATE PROCEDURE [dbo].[Testimonial_SelectAll]
AS
BEGIN
SELECT * FROM [dbo].Testimonials
END
Hope this will Help !!!