How to update or save image in database in C#

Jak
Jak
Member
908 Points
132 Posts

HI,

how to update image records in database?

Views: 10600
Total Answered: 1
Total Marked As Answer: 1
Posted On: 10-Jan-2015 21:22

Share:   fb twitter linkedin
Answers
Rahul Maurya
Rahul M...
Teacher
4826 Points
23 Posts
         

How are you storing the images? The basic idea is to have a FileUpload control so you can browse new image for update.

You can then update the image from your database just like updating normal data in your database. The idea is to get the existing ID of the row that holds your image and then update it with the new image (either update the path or the image itself ~ that depends on how you store the images).

Here's an example: 

private void StartUpLoad(){ 
//get the image file that was posted (binary format) 
byte[] theImage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(theImage, 0, (int)FileUpload1.PostedFile.ContentLength); 
int length = theImage.Length; //get the length of the image 
string fileName = FileUpload1.FileName.ToString(); //get the file name of the posted image 
string type = FileUpload1.PostedFile.ContentType; //get the type of the posted image 
int size = FileUpload1.PostedFile.ContentLength; //get the size in bytes that 
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{ 
//Call the method to execute update in your database
Update(theImage, type, size, fileName, length);
Response.Write("Save Successfully!");
}
}
 
private void Update(int ID, string brand, decimal price, string description,byte[] image){ 
using (SqlConnection connection = new SqlConnection("YOUR CONNECTION STRING HERE")) { 
string sql = "UPDATE YourTableName SET Brand = @Brand, Price = @Price, Description = @Description, Image = @Image WHERE ID = @ID"; 
using (SqlCommand cmd = new SqlCommand(sql, connection)) {
connection.Open();
cmd.Parameters.AddWithValue("@ID", ID);
cmd.Parameters.AddWithValue("@Brand", brand);
cmd.Parameters.AddWithValue("@Price", price);
cmd.Parameters.AddWithValue("@Description", description);
cmd.Parameters.AddWithValue("@Image", image);
cmd.ExecuteNonQuery();
}
}
}
protected void Button1_Click(object sender, EventArgs e){
StartUpLoad();
}
 
Posted On: 10-Jan-2015 21:36
 Log In to Chat