2016-07-23 67 views
0

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[]'.误差的图像DATATYPES

嗨,只想问如何解决这一问题?我无法使用c#在mysql中查看保存的查询。我使用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(); 
     } 
    } 
} 

回答

0

把右列

$字节[]的ImageData =(字节[])dt.Rows [0] [1]) ;

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

这意味着你选择的列是字符串类型不能被转换为字节..

+0

感谢先生:)对不起,浪费你的时间,我只是在编程初学者。我应该在那里放什么?我还没有想法添加图像并在视窗窗体中检索它。 TIA。 :) –

+0

[请尝试此链接](http://www.c-sharpcorner.com/UploadFile/8ea152/fetch-image-from-database-in-windows-form-application/):) –