0

I am storing images to the database on table called test contain (id,name,image), but when I try to Retrieve images by using this code :

SqlConnection CN = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("select * from test where id ='"+txtid.Text+"'", CN);
SqlDataReader myreader;
try
{
    CN.Open();

    myreader = cmd.ExecuteReader();
    if (myreader.HasRows)
    {
        txtid.Text = myreader[0].ToString();
        txtname.Text = myreader[1].ToString();
        byte[] img = (byte[])(myreader[2]);
        if (img == null)
            pictureBox1.Image = null;
        else
        {
            MemoryStream ms = new MemoryStream(img);
            pictureBox1.Image = Image.FromStream(ms);
        }
    }
    else
    {
        MessageBox.Show("do not found");
    }

    CN.Close();
}
catch (Exception ex)
{ MessageBox.Show(ex.Message); }

I have this error : invalid attempt to read when no data is present.

Cédric Bignon
  • 12,892
  • 3
  • 39
  • 51
user2536447
  • 13
  • 3
  • 5
  • 8

1 Answers1

0

HasRows just determines whether there are rows. You also need to Read() to get the reader to advance.

Something like this should work (assuming you just want one row).

myreader = cmd.ExecuteReader();
if (myreader.Read())
{
...

Also be sure to parameterize your SQL select - at the moment it is vulnerable to SQL Injection attacks, and to Dispose of things like the MemoryStream and DataReader

Community
  • 1
  • 1
StuartLC
  • 104,537
  • 17
  • 209
  • 285