【问题标题】:picture from datagridview to picturebox图片从datagridview到picturebox
【发布时间】:2017-02-21 12:19:18
【问题描述】:

我在 c# 中有一个带有 datagridview 的 winform 应用程序,女巫从 sql 数据库中获取它的值,但是当我从 de datagridview 中单击一行时,数据将显示在要编辑的文本框中。 问题是可以编辑的列之一是图像。 我可以上传图像并在数据网格中查看它,但是当我单击行标题以选择时出现错误:“格式不正确的输入字符字符串” 代码是:

private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString());

    MemoryStream ms = new MemoryStream((byte[])dataGridView1.CurrentRow.Cells[2].Value);
    pictureBox1.Image = Image.FromStream(ms);
    desc2.Text = dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString();
    tipo.Text = dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString();
    prumos.Text = dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString();  
}

提前致谢,

【问题讨论】:

  • 您在哪一行得到异常?似乎和Convert.ToInt32的关系比图片还多……
  • @OfirWinegarten 不幸的是,系统没有抛出异常。我只收到错误,表单关闭,我被发送回之前的表单。
  • @OfirWinegarten 我试图评论转换行,现在我收到错误:无法将 System.string 类型的对象关联到 System.byte
  • 好的,所以首先向您的dataGridView1_RowHeaderMouseClick 添加一个try catch。显然,您在这里几乎没有问题。不同列的类型是什么?
  • @OfirWinegarten 列的类型除了图片之外都是文本

标签: c# sql datagridview


【解决方案1】:

您的第一个问题来自Convert.ToInt32,与Image无关。确保文本仅包含数字。

Image的第二个问题可以这样完成:

var imageCell = (DataGridViewImageCell)dataGridView1.CurrentRow.Cells[2];
pictureBox1.Image = (Image)imageCell.Value;

更新 - 以上是错误的

问题是错误的索引,比如写在 cmets 中: 正确的代码是:

MemoryStream ms = new MemoryStream((byte[])dataGridView1.CurrentRow.Cells[0].Value‌​); 
pictureBox1.Image = Image.FromStream(ms);

【讨论】:

  • 我尝试了您的解决方案,但在行出现错误:pictureBox1.Image = Image.FromStream((Image)imageCell.Value);无法从 ´system.drawings.image 转换为 system.IO.stream
  • Grrr 仍然出现相同的错误:\ 我会从表单上传屏幕截图,也许这是另一个原因
  • 我添加了截图
  • 仍然输入格式不正确的字符串
  • 对我来说,您似乎尝试了错误的字段索引。从快照看起来图像在索引 0 而不是 2 中。而你的 int 是索引 3 而不是 1
【解决方案2】:

我认为您缺少索引。试试first(id) 单元格 0。

ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());

【讨论】:

    猜你喜欢
    • 2021-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-18
    相关资源
    最近更新 更多