尝试将数据库中的字节转换为要显示的图像时,到达此行时:
Image image = Image.FromStream(ms);
代码将以不同的形式跳转到表单加载。这有什么理由呢?
其余代码:
private void dataGridView2_SelectionChanged(object sender, EventArgs e)
{
//try
//{
if (dataGridView2.SelectedCells.Count > 0)
{
int selectrowindex = dataGridView2.SelectedCells[0].RowIndex;
DataGridViewRow selectrow = dataGridView2.Rows[selectrowindex];
productID = Convert.ToString(selectrow.Cells[0].Value);
productName.Text = Convert.ToString(selectrow.Cells[1].Value);
productDetails.Text = ("Desc: " + Convert.ToString(selectrow.Cells[2].Value));
productPrice.Text = (Convert.ToString(selectrow.Cells[4].Value));
productStock.Text = Convert.ToString(selectrow.Cells[5].Value);
db_connection();
SqlCommand cmd = new SqlCommand("SELECT Image FROM PRODUCTS WHERE ProductID = @ProductID", connect);
cmd.Parameters.AddWithValue("ProductID", productID);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
byte[] img = (byte[])(reader[0]);
if (img == null)
{
MessageBox.Show("Theres no image");
productPictureDisplay.Image = null;
}
else
{
MemoryStream ms = new MemoryStream(img);
Image image = Image.FromStream(ms);
productPictureDisplay.Image = image;
}
}
connect.Close();
}
}
答案 0 :(得分:0)
尝试如下,并开始在代码中使用using
,以便通过它处理事物(连接对象,内存流)
public Image byteArrayToImage(byte[] byteArrayIn)
{
try
{
var ms = new MemoryStream(byteArrayIn);;
return Image.FromStream(ms);
}
catch(Exception ex)
{ console.WriteLine(ex.Tostring()); }
return returnImage;
}