【发布时间】:2019-07-29 22:24:49
【问题描述】:
我在 DataGridView 中从 MySQL 加载数据,并尝试将数据从网格视图显示到文本框和图片框。当我尝试将图像从 datagridview 加载到图片框时,它会引发异常。我浪费了 2 天的时间来解决它,但我仍然没有成功。
这是我单击单元格时遇到的异常:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
try
{
id.Text = dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString();
name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
cost.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
price.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
status.Text = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
description.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
//picture.Image = (Image)dataGridView1.Rows[e.RowIndex].Cells[0].Value;
if (dataGridView1.Rows[e.RowIndex].Cells[5].Value != DBNull.Value)
{
MemoryStream ms = new MemoryStream((byte[])dataGridView1.Rows[e.RowIndex].Cells[5].Value);
picture.Image = Image.FromStream(ms); // here is exception
}
else
{
picture.Image = null;
}
}
catch (Exception ex)
{
MessageBox.Show("Error " + ex);
}
}
【问题讨论】:
-
我认为为了让它起作用,你的
MemoryStream必须是一个真实的图像。换句话说,数据需要采用某种图像格式,但显然不是。 -
如果您确定您实际上是在单击图像,则应尝试从事件处理程序的参数中检索该图像,而不是直接从网格中检索。
-
什么是
dataGridView1.Rows[e.RowIndex].Cells[5].Value?你是怎么把它放在那里的?与其从网格中读取,不如尝试首先从您获取数据的来源(查询到数据库等)。如上所述,它应该是二进制数组,或者类似的东西(图像的二进制表示);您的网格中不太可能有此类信息。 -
@RobertHarvey 我没有点击图片,而是点击了一行,因此整行的数据在文本框和图片框中移动
-
能否从事件参数中获取整行?
标签: c# mysql datagridview