2012-02-28 24 views
1

我有這個代碼;我得到的未處理的SQLException來自哪裏?

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     SqlConnection cnn; 
     string connectionString; 
     connectionString = "server=.\\sqlexpress;database=Blue;trusted_connection=true"; 
     cnn = new SqlConnection(connectionString); 

     MemoryStream stream = new MemoryStream(); 
     cnn.Open(); 
     SqlCommand command = new SqlCommand("select Image from ImageParts where ImageName=" + listBox1.SelectedIndex, cnn); 
     byte[] image = (byte[])command.ExecuteScalar(); 
     stream.Write(image, 0, image.Length); 
     cnn.Close(); 
     Bitmap bitmap = new Bitmap(stream); 
     pictureBox1.Image = bitmap; 
    } 

我已經存儲在listBox1.Items

然後ImageName,該錯誤出現。

將varchar值'c1.jpg'轉換爲數據類型爲int的數據 時轉換失敗。

可能是什麼問題?由於我是C#的新手,我不熟悉這些錯誤。

回答

1

它看起來像您的數據庫中的ImageName字段的數據類型爲int,並且您將一個string傳遞給它(varchar)。

驗證並更正數據庫中的數據類型ImageName

+0

我同意鯊魚,這裏的問題是數據類型不匹配 – 2012-02-28 20:07:21

1

我想你的數據庫中的ImageName列是一個字符串類型,而不是一個int類型。您將索引而不是圖像的名稱傳遞給您的SqlCommand。如果是這種情況,請不要忘記在字符串周圍使用單引號。

string nameImg = listBox1.SelectedItem.ToString(); 
SqlCommand command = new SqlCommand("select Image from ImageParts where ImageName = '" + nameImg + "'"); 

在這裏,我想你的列表框填充您的圖像

0

隨着什麼史蒂夫說你也應該換你的代碼中的SQL命令try catch塊休息,看到的字符串名稱是什麼值是正在發送到服務器。在你的立即窗口或手錶中獲取command.CommandText.ToString(),複製該值,然後嘗試在SSMS中解析它並查看會發生什麼並相應地調整字符串。從現在開始,你可以看到它失敗的原因,並在事情失敗時在程序中相應地處理錯誤。