Start New Discussion within our Software Development Community

This is the simple code to read an image from the database.

private void button1_Click(object sender, System.EventArgs e) 
{
      if (images.GetRow())
   {
         this.textBox1.Text = images.GetFilename();
         this.pictureBox1.Image = (Image)images.GetImage();
      } 
else 
{
         this.textBox1.Text = "DONE";
         this.pictureBox1.Image = null;
      }
   }
}


public class Images{
   string imageFilename = null;
   byte[] imageBytes = null;

   SqlConnection imageConnection = null;
   SqlCommand imageCommand = null;
   SqlDataReader imageReader = null;

   public Images() {
      imageConnection = new SqlConnection("server=(local)\\SQLEXPRESS;database=MyDatabase;Integrated Security=SSPI");
      imageCommand = new SqlCommand(@"select imagefile, imagedata from imagetable", imageConnection);

      imageConnection.Open();
      imageReader = imageCommand.ExecuteReader();
   }

   public Bitmap GetImage() {
      MemoryStream ms = new MemoryStream(imageBytes);
      Bitmap bmap = new Bitmap(ms);

      return bmap;
   }

   public string GetFilename() {
      return imageFilename;
   }

   public bool GetRow() {
      if (imageReader.Read()) {
        imageFilename = (string) imageReader.GetValue(0);
        imageBytes = (byte[]) imageReader.GetValue(1);
        return true;
      }else {
        return false;
      }
   }

   public void EndImages() {
      imageReader.Close();
      imageConnection.Close();
   }
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.