Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
SqlConnection connection = new SqlConnection("data source=.; initial catalog=jai; uid=sa; pwd=12345");
        string sql = "SELECT ProductName, ProductImage FROM image WHERE ImageID = @ImageID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ImageID", theID);
        connection.Open();
        object theImg = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])theImg);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }
Posted
Updated 7-Nov-12 21:49pm
v2

Check the documentation for ExecuteScalar():

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx[^]

"Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored"

Your query is:

C#
string sql = "SELECT ProductName, ProductImage FROM image WHERE ImageID = @ImageID";


Which means you're trying to cast ProductName to a byte[]

Either amend your query to:

C#
string sql = "SELECT ProductImage FROM image WHERE ImageID = @ImageID";


or think about using an ORM like an ADO.net DataSet or Entity Framework model if you need to return more than just the ProductImage column.
 
Share this answer
 
Comments
jairam1290 8-Nov-12 6:47am    
thank u
jim lahey 8-Nov-12 6:57am    
My pleasure. If the answer to your question was correct, please mark it and rate it for future reference.

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