无法从数据库中检索图像

时间:2013-12-06 04:45:43

标签: c# sql-server wpf

我希望在单击按钮时从我的SQL Server数据库中检索图像(以二进制格式)。但是当我点击按钮时会发生错误:

  

System.InvalidOperationException {“没有数据时无效尝试读取。”}

代码:

 private void onSearchClick(object sender, RoutedEventArgs e) {
        SqlConnection conn;
        SqlCommand cmdSelect;
        SqlDataReader reader;

        string connStr =     ConfigurationManager.ConnectionStrings["house"].ConnectionString;
        conn = new SqlConnection(connStr);

        String strSelect = "Select FoodName, Images From Food where FoodName = @foodName";
        cmdSelect = new SqlCommand(strSelect, conn);
        cmdSelect.Parameters.AddWithValue("@foodname", comboBox1.SelectedValue.ToString());
        conn.Open(); 
        reader = cmdSelect.ExecuteReader();

        //retrieve image
        byte[]blob = (byte[])reader["Images"];
        MemoryStream stream = new MemoryStream();
        stream.Write(blob, 0, blob.Length);
        stream.Position = 0;
        System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
        BitmapImage bi = new BitmapImage();
        bi.BeginInit();
        MemoryStream ms = new MemoryStream();
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
        ms.Seek(0,SeekOrigin.Begin);
        bi.StreamSource = ms;
        bi.EndInit();
        image6.Source = bi;

        try {                             
            while (reader.Read()) {
                String nameOfFood = reader["FoodName"].ToString();
            }
            conn.Close();
        }
        catch(Exception ex){
            MessageBox.Show(ex.Message);
        }

1 个答案:

答案 0 :(得分:1)

reader = cmdSelect.ExecuteReader();

你必须致电

reader.Read();

从db读取第1行。 更好的

if (reader.Read())
{
  //query returns some data and you may get image from reader fields
}