user3016854
user3016854

Reputation: 17

Cannot retrieve image from database

I want to retrieve images (in binary format) from my SQL Server database on a button click. But when I click on the button an error occurs:

System.InvalidOperationException {"Invalid attempt to read when no data is present."}

Code:

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

Upvotes: 0

Views: 228

Answers (1)

Dmytro Rudenko
Dmytro Rudenko

Reputation: 2524

after

reader = cmdSelect.ExecuteReader();

you have to call

reader.Read();

for reading 1st row from db. Even better

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

Upvotes: 1

Related Questions