我正在尝试从Datagridview中投射图像并显示为我已将其修改器设置为public的表单。我收到此错误
发生了'System.InvalidCastException'类型的未处理异常
其他信息:无法转换'System.Byte []'类型的对象 输入'System.Drawing.Image'。
在这一行
InformationForm info = new InformationForm();
info.visit_date.Text = this.dataGridView1.CurrentRow.Cells[0].Value.ToString();
info.visitor_name.Text = this.dataGridView1.CurrentRow.Cells[1].Value.ToString();
info.sign_intime.Text = this.dataGridView1.CurrentRow.Cells[2].Value.ToString();
info.vehicle_number.Text = this.dataGridView1.CurrentRow.Cells[3].Value.ToString();
info.organization.Text = this.dataGridView1.CurrentRow.Cells[4].Value.ToString();
info.visit_type.Text = this.dataGridView1.CurrentRow.Cells[5].Value.ToString();
info.reason.Text = this.dataGridView1.CurrentRow.Cells[6].Value.ToString();
info.id_type.Text = this.dataGridView1.CurrentRow.Cells[7].Value.ToString();
info.person_visit.Text = this.dataGridView1.CurrentRow.Cells[8].Value.ToString();
info.pictureBox.Image = byteArrayToImage(dataGridView1.CurrentRow.Cells[9].Value); // on this line
info.ShowDialog();
并没有在图片框中显示。我错了什么?
答案 0 :(得分:1)
您无法将System.Byte[]
投射到Image
,您必须创建一个新的Image
对象。试试这样:
info.pictureBox.Image = byteArrayToImage((byte[])dataGridView1.CurrentRow.Cells[9].Value);
以下是方法:
public Image byteArrayToImage(byte[] byteArray)
{
MemoryStream ms = new MemoryStream(byteArray);
Image img = Image.FromStream(ms);
return img;
}
答案 1 :(得分:0)
这可能适合你:
由于你有一个图像作为数据库或某个地方的字节数组,你只需要转换并显示它:
using (var ms = new MemoryStream(dataGridView1.CurrentRow.Cells[9].Value))
{
info.pictureBox.Image = Image.FromStream(ms);
}