图像数据中的错误

时间:2016-07-23 06:53:24

标签: c# mysql

An unhandled exception of type 'System.InvalidCastException' occurred in WindowsFormsApplication1.exe and Additional information: Unable to cast object of type 'System.String' to type 'System.Byte[]'.

嘿伙计们,我想问一下如何解决这个问题?我无法使用c#在mysql中使用image查看我保存的查询。我使用blob数据类型在mysql中保存图像。我是一名大学生,我们现在正在学校开展IT项目:)期待答案:) Godbless。 TIA。 :d

这是我的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using MySql.Data.MySqlClient;


namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }


        private void button2_Click(object sender, EventArgs e)
        {

            string connStr = "server = 127.0.0.1; uid = root; " + "pwd =; database = dbSample";
            MySqlConnection con = new MySqlConnection(connStr);
            MySqlCommand cmd;
            MySqlDataAdapter da;
            string query = "select * from image where name = '" + txtFirstname.Text + "' ";
            cmd = new MySqlCommand(query, con);
            da = new MySqlDataAdapter();
            DataTable dt = new DataTable();
            da.SelectCommand = cmd;
            da.Fill(dt);

            txtFirstname.Text = dt.Rows[0][0].ToString();
            byte[] ImageData = (byte[])dt.Rows[0][1];       // <----this is the error.
            MemoryStream ms = new MemoryStream(ImageData);
            pictureBox1.Image = Image.FromStream(ms);

            da.Dispose();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

放右栏

$ byte [] ImageData =(byte [])dt.Rows [0] [1]);

查找  “无法将'System.String'类型的对象强制转换为'System.Byte []'。”

这意味着您选择的列是无法转换为字节的字符串类型..