【问题标题】:"Failed to convert parameter value from a DataRowView to a Int32" message on running a code运行代码时出现“无法将参数值从 DataRowView 转换为 Int32”消息
【发布时间】:2015-08-10 18:58:18
【问题描述】:

我正在尝试从 .Net 加载存储在 SQL 服务器上的一些图像数据,但是在屏幕上开始出现错误并显示以下消息时:无法将参数值从 DataRowView 转换为 Int32 但我不知道问题出在哪里。

本部分代码:

try
    {
    conn.Open();
    strSQL = "SELECT * FROM Pictures WHERE ID = @ID";
    da = new SqlDataAdapter(strSQL, conn);
    da.SelectCommand.Parameters.Add("@ID" ,SqlDbType.Int).Value = listBox1.SelectedValue;
    ds = new DataSet();
    da.Fill(ds, "Pictures");
    byte[] arrPic = (byte[])(ds.Tables["Pictures"].Rows[0]["Pic"]);
    MemoryStream ms = new MemoryStream(arrPic);
    pictureBox1.Image = Image.FromStream(ms);
    conn.Close();
}
catch (SystemException ex)
{
    MessageBox.Show(ex.Message);
}

错误出现在“da.Fill(ds, "Pictures");”上

【问题讨论】:

  • 所以listBox1.SelectedValue 不是整数,
  • 可能与this重复

标签: c# .net sql-server-2008


【解决方案1】:
listBox1.SelectedValue

返回一个对象,而不是整数。尝试像这样转换它

 da.SelectCommand.Parameters.Add("@ID" ,SqlDbType.Int).Value = Convert.ToInt32(listBox1.SelectedValue);

正如@Kevin 在他的cmets 中指出的那样,如果listBox 实际上返回整个DataRowView,您可能必须使用不同的方法。类似的东西

DataRowView drv = (DataRowView)listBox1.SelectedItem;
String valueOfItem = drv["TheColumnYouActuallyWant"].ToString();
da.SelectCommand.Parameters.Add("@ID" ,SqlDbType.Int).Value = Convert.ToInt32(valueOfItem);

this问题所示。

【讨论】:

  • 问题是“DataRowView to a Int32”,ListBox.SelectedValue 可以返回一个DataRowView 吗?如果是这样的话,一定是在做一些非常奇怪的事情......
  • @Stone 是的,老实说不知道。无论如何,假设实际值是一个 int,这应该可以工作。如果不是......好吧......谁知道大声笑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-09
  • 1970-01-01
  • 2019-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多