Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
How can a image in a picture box be insert into a table in the database?

C#
private void button3_Click(object sender, EventArgs e)  //Add button
{
 if (textBox1.Text == "" ||textBox2.Text==""|| pictureBox1.Container == null || pictureBox2.Container == null)
   MessageBox.Show("Please make sure to enter the name and pictures!!");
            
 else//add pictures to table
 {
  try
   {
    string dbconnstr = @"C:\Users\compaq\Desktop\new\n1\ClassLibrary1\Database1.mdf;Integrated Security=True;User Instance=True";
    SqlConnection conn = new SqlConnection(dbconnstr);
    conn.Open();
    string qry = "insert into pic values (pictureBox1.Image)"; 

    //Initialize SqlCommand object for insert.
    SqlCommand sqlcom = new SqlCommand(qry,conn);
    sqlcom.BeginExecuteNonQuery();                                     
                    conn.Close();
                    conn.Dispose();
   }
  catch (Exception ee)
   {string error = ee.Message;}
}


This code doesn't insert pictures to table, even there are no errors to be found.

Please help.
Posted
Updated 29-May-11 4:39am
v2

 
Share this answer
 
Comments
Kim Togo 29-May-11 12:14pm    
My 5 for the link.
Espen Harlinn 29-May-11 14:35pm    
Nice howto, my 5
Try this Load/Unload images into/from DB table[^] and C# Save and Load Image from Database[^]

There are many articles here at CP that can help you. Try search :-)
 
Share this answer
 
Comments
yesotaso 29-May-11 10:59am    
If I may add:
While writing your question Subject you'd notice a Related Entries column which also brings up related posts you are trying to ask, which can serve as implicit search :P
Kim Togo 30-May-11 2:26am    
Implicit search, yes you are right :-)
Nope. It won't. Why? because "picturebox1.Image" is a string. Not an image.
If you have the field configured in your database, then try:
SqlConnection conn = new SqlConnection(dbconnstr);
conn.Open();
string qry = "INSERT INTO myTable (myImageField) VALUES (@PD)";
 //Initialize SqlCommand object for insert.
SqlCommand sqlcom = new SqlCommand(qry,conn);
MemoryStream ms = new MemoryStream();
pictureBox1.Image.Save(ms,System.Drawing.Imaging.ImageFormat.Bmp);
sqlcom.Parameters.AddWithValue("@PD", ms.ToArray());
sqlcom.ExecuteNonQuery();
 
Share this answer
 
Comments
Kim Togo 29-May-11 12:16pm    
Really good answer Griff. My 5.
You read the actual SQL statement and found a error her.
OP has the answer her :-)
 
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