如何在C#〔Windows应用程序〕中从SQL Server 2008 R2中检索映像到Datagridview
本文关键字:R2 2008 Server 检索 Datagridview 映像 SQL 中从 Windows 应用程序 | 更新日期: 2023-09-27 17:59:53
朋友们,我已经将图像插入到Sql Server中,我需要从Sql Server 2008 R2中检索图像到C#中的Datagridview列中。有没有可能将数据网格视图中的图像显示为网格视图列中的任意相应大小。
我将图像插入SQL Server的编码是:
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;
}
请尝试解决此问题。感谢
存储到数据库(在数据库中,imagedata
列必须具有IMAGE
数据类型)
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();
从数据库检索
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();