【问题标题】:Unable to cast object of type 'system.byte ' to type 'system.iconvertible'无法将“system.byte”类型的对象转换为“system.iconvertible”类型
【发布时间】:2015-06-02 18:33:55
【问题描述】:

我总是得到错误

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

使用我通过列表视图的“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;
}

我在哪里做错了?

【问题讨论】:

  • 在哪一行抛出异常?
  • 字节位 = Convert.ToByte(ds.Tables[0].Rows[0][0]);
  • 我很确定您的位图没有存储在单个字节中……
  • 单字节图像?你确定你真的不想要一个字节数组吗? (字节[])
  • 它说..“参数无效。”当我使用 byte[].

标签: c# casting


【解决方案1】:

只是一个疯狂的猜测:我认为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 框架)。

【讨论】:

  • 参数无效。它说.. :(
  • 这正是我想说的。
  • @JamesAndrewCruz 确保您传入的任何内容都是 convert.tobyte 方法接受的类型,列表在这里:msdn.microsoft.com/en-us/library/system.convert.tobyte.aspx
  • 这是 C#,不是 VB。我认为您的 Field() 语法错误。应该是Field&lt;Byte[]&gt;("DVDImage")
【解决方案2】:

尝试替换

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

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

【讨论】:

  • '参数无效'它说... :(
  • 它是在哪一行写的?
  • 参数在他的行上无效:Bitmap bitmap = new Bitmap(memoryBits);
  • @JamesAndrewCruz:这是不同原因的不同问题。您可能想就此提出一个新问题。
  • @Heinzi:有趣的是,他确实做到了,而且它作为副本被关闭了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-26
  • 2015-12-17
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多