Click here to Skip to main content
16,020,714 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to display image in Listview using filepath which is stored in sql server 2008 in asp.net ?
Posted

1 solution

HTML Markup
C#
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

 <asp:TemplateField HeaderText="CharacterID">

 <asp:Label ID="lblid" runat="server" Text='<%# Bind("ID") %>'>


 <asp:TemplateField HeaderText="Image">

 <asp:Image ID="Image1" runat="server" ImageUrl='<%#"ShowImage.ashx?getID="+Eval("ID") %>' />
</ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>




Code behind:
C#
protected void Page_Load(object sender, EventArgs e)
{        
    DataTable dt = getData();
    GridView1.DataSource = dt;
    GridView1.DataBind();
  }

public  DataTable getData() 
{
  SqlDataAdapter dap = new SqlDataAdapter("select ID,Image from table", cn);
  DataSet ds = new DataSet();
  dap.Fill(ds);
  return ds.Tables[0];
}


Generic handler: Add new generic handler here showIamges.ashx is my generic handler
C#
public void ProcessRequest(HttpContext context)
 {
    Int32 my_Id;
    if (context.Request.QueryString["getID"] != null)
    {
       my_Id = Convert.ToInt32(context.Request.QueryString["getID"]);
       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(my_Id);
       byte[] buffer = new byte[4096];
       int byteSeq = strm.Read(buffer, 0, 4096);
       while (byteSeq > 0)
        {
           context.Response.OutputStream.Write(buffer, 0, byteSeq);
           byteSeq = strm.Read(buffer, 0, 4096);
        }
      }
}

public Stream ShowEmpImage(int my_Id)
{
   string conn = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
   SqlConnection connection = new SqlConnection(conn);
   string sql = "select image from tableWHERE ID = @ID";
   SqlCommand cmd = new SqlCommand(sql, connection);
   cmd.CommandType = CommandType.Text;
   cmd.Parameters.AddWithValue("@ID", my_Id);
   connection.Open();
   object img = cmd.ExecuteScalar();
   return new MemoryStream((byte[])img);
 }
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900