异常'System.ArgumentException'

时间:2019-07-29 22:24:49

标签: c# mysql datagridview

我正在DataGridView中从MySQL加载数据,并试图将数据从网格视图显示到文本框和图片框。当我尝试将图像从datagridview加载到图片框时,它将引发异常。我已经浪费了我的两天时间来解决它,但仍然失败。

这是我单击单元格时遇到的异常:

Image

 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);
        }
    }

1 个答案:

答案 0 :(得分:0)

如果图像的二进制表示格式不正确,则会出现此错误:

var imageBytes = Convert.FromBase64String(@"Qk16AAAAAAAAAHYAAAAoAAAAAQAAAAEAAAABAAQAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAgAAAAICAAIAAAACAAIAAgIAAAICAgADAwMAAAAD/AAD/AAAA//8A/wAAAP8A/wD//wAA////APAAAAA=");
var img = Image.FromStream(new MemoryStream(imageBytes)); // ok


var badImageBytes = Convert.FromBase64String(@"Qk16AAAAAAAAAHYAAAAoAAAAAQAAAAEAAAABAAQAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAgAAAAICAAIAAAACAAIAAgIAAAICAgADAwMAAAAD/AAD/AAAA//8A/wAAAP8A/wD//wAA////APAAAA==");
var badImg = Image.FromStream(new MemoryStream(badImageBytes )); // not ok

检查值一致性的最简单方法是将其保存到文件中,然后尝试使用任何图像查看器打开。

var bytes = (byte[])dataGridView1.Rows[e.RowIndex].Cells[5].Value;
File.WriteAllText(@"C:\Temp\image.base64.txt", Convert.ToBase64String(bytes)); // if image is not confidential you may share it with the community in the comment
File.WriteAllBytes(@"C:\Temp\image.bmp", bytes);

请注意,仅支持following image formats

  • BMP
  • GIF
  • JPEG
  • PNG
  • TIFF

格式错误的原因可能有所不同:

  • 有人上传了无效的图片
  • 有一些数据转换(压缩/加密)
  • 数据在存储中被截断(如果是SQL,请检查列的DDL)