Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi, how do you retrieve a image datatype from database and load the image to your label.

In my database, the image column is BINARY DATA

I tried this and it shows system.byte[]

//code for retrieving
string pt = dr["Photo"].ToString();
image = Encoding.ASCII.GetBytes(pt);
Posted
Updated 2-Jun-14 2:30am
v3
Comments
TrushnaK 2-Jun-14 8:26am    
What you want to ask? Improve your question
[no name] 2-Jun-14 8:28am    
You would do a tiny bit of research and write some code.
Raul Iloc 2-Jun-14 8:34am    
Which type of application do you use? ASP.NET MVC, WCF, Windows Froms?
anoym0us 2-Jun-14 8:37am    
ASP.NET MVC

Here's one way to retrieve the binary field and convert it to an image.
SqlConnection conn = ...;
SqlCommand cmd = new SqlCommand ("SELECT img FROM images WHERE imgId = 42", conn);
SqlDataAdapter dataAdapter = new SqlDataAdapter();
DataSet dataSet = new DataSet();
dataAdapter.Fill (dataSet);
if (dataSet.Tables[0].Rows.Count == 1) {
    Byte[] data = new Byte[0];
    data = (Byte[])(dataSet.Tables[0].Rows[0]["img"]);
    using (MemoryStream ms = new MemoryStream (data)) {
      myLabel.Image= Image.FromStream (ms);
    }
}
/ravi
 
Share this answer
 
Comments
anoym0us 2-Jun-14 8:36am    
hi my label is in the aspx.cs, and my retrieve method is not the code behind but another cs
If you don't understand why, then the chances are both bits of your code are wrong: the INSERT into the database and the SELECT to fetch the image back.

Have a look here: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^] - it explains what you are doing wrong, and shows you how to do it properly.
 
Share this answer
 
Use this function to retrieve image from database

Create a handler file and use this code.

VB
Public Function ShowEmpImage(ByVal ID As Integer) As Stream
        Try
            con = New SqlConnection(DB.GetCon)
            Dim sql As String = "SELECT top 1 Image  FROM tablname WHERE ID= @ID"
            Dim cmd As SqlCommand = New SqlCommand(sql, con)
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@ID", ID)
            con.Open()
            Dim img As Object = cmd.ExecuteScalar()
            Return New MemoryStream(CType(img, Byte()))

        Catch
            Return Nothing
        Finally
            con.Close()
        End Try
    End Function
 
Share this answer
 

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