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.

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.