1

I'm trying to load some image data stored on SQL server from .Net but while starting an error appearances on screen with a message : Failed to convert parameter value from a DataRowView to a Int32 But I don't know where is the problem.

Code of this part:

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

Error is on "da.Fill(ds, "Pictures");"

Shaho
  • 182
  • 2
  • 14

1 Answers1

2
listBox1.SelectedValue

returns an object, not an integer. Try converting it like

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

as @Kevin pointed out in his comments, you may have to use a different approach if the listBox is actually returning an entire DataRowView. Something like

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

as illustrated in this question.

Community
  • 1
  • 1
psoshmo
  • 1,490
  • 10
  • 19
  • 1
    The question states "DataRowView to a Int32", can `ListBox.SelectedValue` return a `DataRowView`? Must be doing something really strange if so... – Stone Aug 10 '15 at 19:09
  • @Stone yea, honestly have no idea. Regardless though, assuming the actual value is an int, this should work. if it isnt....well....who knows lol – psoshmo Aug 10 '15 at 19:12