无法将'system.byte'类型的对象强制转换为'system.iconvertible'类型

时间:2012-02-19 10:55:32

标签: c# casting

我总是收到错误

  

无法将'system.byte'类型的对象转换为'system.iconvertible'

使用我的代码通过listview的'SelectedIndexChanged'事件将图像表格DB检索到图片框。

这是我的代码:

foreach (ListViewItem LVI in lvwInventory.SelectedItems)
{
    ////CONNECTION STRING TO THE DATABASE (USED FOR SAVING/UPLOADING IMAGE)
    //System.Data.OleDb.OleDbConnection con = new System.Data.OleDb.OleDbConnection("Provider=microsoft.jet.oledb.4.0; data source=..\\dbMyDVDOrganizer.mdb");
    con.Open();
    //OLEDB COMMAND FOR RETRIEVING IMAGE FROM THE DATABASE
    System.Data.OleDb.OleDbCommand cmd = new System.Data.OleDb.OleDbCommand("SELECT DVDImage FROM tblDVDInventory WHERE ItemCode='" + lvwInventory.SelectedItems[0].Text + "'");
    cmd.Connection = con;
    cmd.CommandType = CommandType.Text;
    System.Data.OleDb.OleDbDataAdapter da = new System.Data.OleDb.OleDbDataAdapter(cmd);
    DataSet ds = new DataSet();
    da.Fill(ds);
    Byte bits = Convert.ToByte(ds.Tables[0].Rows[0][0]);
    MemoryStream memoryBits = new MemoryStream(bits);
    Bitmap bitmap = new Bitmap(memoryBits);
    //BITMAP HAS THE IMAGE NOW.
    pctImage.Image = bitmap;
}

我在哪里弄错了?

2 个答案:

答案 0 :(得分:4)

只是一个疯狂的猜测:我的图像DVDImage包含的不只是Byte ...也许是一个字节数组(Byte[])?取代

Byte bits = Convert.ToByte(ds.Tables[0].Rows[0][0]);

Byte[] bits = ds.Tables[0].Rows[0].Field<Byte[]>("DVDImage");

(或

Byte[] bits = (byte[])(ds.Tables[0].Rows[0][0]);

如果您使用的是旧版本的.NET框架。)

答案 1 :(得分:0)

尝试替换

Byte bits = Convert.ToByte(ds.Tables[0].Rows[0][0]);

Byte[] bits = (Byte[])ds.Tables[0].Rows[0][0];