C# 从Datagrid到另一个Winform发生类型为“System.InvalidCastException”的未处理异常

C# 从Datagrid到另一个Winform发生类型为“System.InvalidCastException”的未处理异常,c#,datagridview,C#,Datagridview,我试图从Datagridview中转换一个图像,并将其显示为一个我已将其修改器设置为public的表单。我得到这个错误 发生类型为“System.InvalidCastException”的未处理异常 其他信息:无法强制转换类型为“System.Byte[]”的对象 键入“System.Drawing.Image” 在这条线上 InformationForm info = new InformationForm(); info.visit_date.Text

我试图从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();
而且它不会显示在图片框中。我做错了什么?

您不能将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;
}

这可能对您很有用:

因为您有一个来自数据库或其他地方的字节数组图像,您只需要转换并显示它:

using (var ms = new MemoryStream(dataGridView1.CurrentRow.Cells[9].Value))
{
    info.pictureBox.Image = Image.FromStream(ms);
}

正如错误消息所示,您所犯的错误是试图将System.Byte[]类型的对象强制转换为System.Drawing.Image类型。如果这些字节中的内容实际上是一个序列化图像,那么您必须找到某种方法来从这些字节构造图像对象。这应该是可行的一点搜索。也有可能你找错了房间;我无法猜测您的datagridview中有什么内容。请查看或提供有关数据如何保存在datagrid中的更多信息。错误:无法从对象转换为字节[]@Markaz:我添加了对字节[]的强制转换。请再试一次,告诉我是否有效。如果没有,我想我将不得不删除答案。尽管如此,谢谢: