【问题标题】:Error in datatype of image (System.InvalidCastException)图像数据类型错误 (System.InvalidCastException)
【发布时间】:2016-07-23 06:53:24
【问题描述】:

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 中查看我保存的带有图像的查询。我在 mysql 中保存图像时使用了 blob 数据类型。我是一名大学生,我们现在正在学校开展 IT 项目。

这是我的代码:

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

【问题讨论】:

    标签: c# mysql


    【解决方案1】:

    放右栏

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

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

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

    【讨论】:

    • 谢谢先生 :) 抱歉浪费您的时间,我只是编程的初学者。我应该在里面放什么?我还没有添加图像并以视图窗口形式检索它的想法。 TIA。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多