Reputation: 1163
Hi friends i have inserted image to Sql Server and i need to retrieve image from SQL Server 2008 R2 to Datagridview Column in C# [Windows Application].Is there any possible to show the image in Data Grid View is any Respective Size in a column of Grid View.
My Coding to Insert the images to SQL Server is :
public void saveImageInDataBase(int imageid)
{
byte[] imagedata = ReadImageFile(txt_upload.Text);
SqlConnection sqlconn = new SqlConnection();
sqlconn.ConnectionString = "Data Source=.;Initial Catalog=db_payroll;Integrated Security=True;";
sqlconn.Open();
string query = "insert into tbl_image values('"+imagedata+"')";
MessageBox.Show(query);
SqlCommand cmd = new SqlCommand(query, sqlconn);
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
MessageBox.Show("Image saved.");
txt_upload.Text = "";
pictureBox1.Image = null;
}
else
{
MessageBox.Show("Unable to save image.");
sqlconn.Close();
}
}
public byte[] ReadImageFile(string imageLocation)
{
byte[] imageData = null;
FileInfo fileInfo = new FileInfo(imageLocation);
long imageFileLength = fileInfo.Length;
FileStream fs = new FileStream(imageLocation, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
imageData = br.ReadBytes((int)imageFileLength);
return imageData;
}
Please try to Solve this issue. Thanks
Upvotes: 0
Views: 3262
Reputation: 33381
Store to DB (in DB the imagedata
column must have IMAGE
data type)
string query = "insert into tbl_image values(@imagedata)";
SqlCommand cmd = new SqlCommand(query, sqlconn);
cmd.Parameters.Add("@imagedata", System.Data.SqlDbType.Image);
cmd.Parameters["@imagedata"].Value = imagedata;
int rows = cmd.ExecuteNonQuery();
To retrieve from DB
string query = "select imagedata from tbl_image where ID=@ID";
SqlCommand cmd = new SqlCommand(query, sqlconn);
cmd.Parameters.AddWithValue("@id", id);
byte[] imagedata=(byte[])cmdSelect.ExecuteScalar();
Upvotes: 4