Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I have a c# winform app that stores images in an sql database as "image".
I can store the image just fine but when a print the report the image does not appear.

Can anyone help, thanks in advance.
The code i use to store the image and print the report is below:

What I have tried:

//insert image in SQL:
C#
con.Open();
MemoryStream ms = new MemoryStream();
pictureBox2.Image.Save(ms, ImageFormat.Jpeg);
byte[] photo = new byte[ms.Length];
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into dbo.temp (maquete) VALUES ('" + Photo + "');
cmd.ExecuteNonQuery();
con.Close();
report report = new report();
report.ShowDialog();



//print report

C#
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from temp";
cmd.ExecuteNonQuery();
bdDataSet ds = new bdDataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds.temp);
hytherm myReport = new hytherm();
myReport.SetDataSource(ds);
crystalReportViewer1.ReportSource = myReport;
con.Close();
Posted
Updated 21-Nov-16 8:35am

NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.

At the moment, using string concatenation, your final query will be:
SQL
insert into dbo.temp (maquete) VALUES ('System.Byte[]')

Clearly, the literal string System.Byte[] is not a valid byte array.

(The byte array is also empty - you declare it, but you never populate it.)

In order to pass a byte array to your query, you must use a parameter:
C#
using (var connection = new SqlConnection("..."))
using (var command = new SqlCommand("INSERT INTO dbo.temp (maquete) VALUES (@photo)", connection))
{
    using (var ms = new MemoryStream())
    {
        pictureBox2.Image.Save(ms, ImageFormat.Jpeg);
        byte[] photo = ms.ToArray();
        command.Parameters.AddWithValue("@photo", photo);
    }
    
    connection.Open();
    command.ExecuteNonQuery();
}


NB: All of the images that you think you've stored in your table so far are corrupt. You will need to remove and re-add them.


Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
 
Share this answer
 
Comments
Marc-IT 22-Nov-16 4:07am    
Many thanks, it finnaly works.
Store and Retrieve Image in Crystal Reports From SQL Database and Folder Using ASP.Net[^]


C#
tp://www.aspsnippets.com/Articles/Display-image-from-database-in-Crystal-Report-in-ASPNet-using-C-and-VBNet.aspx
 
Share this answer
 
v2

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