Bags Banny
Bags Banny

Reputation: 137

Fetch Image from Database

I have this code to display Image from SQL Server 2008 Database to a pictureBox

using (SqlCommand SqlCommand = new SqlCommand("Select * From Student Where StudentID = @a", myDatabaseConnection))
{
   SqlCommand.Parameters.AddWithValue("@a", SearchtextBox.Text);

   DataSet DS = new DataSet();

   SqlDataAdapter da = new SqlDataAdapter(SqlCommand);
   da.Fill(DS, "Images");

   dataGridView1.DataSource = DS.Tables[0];
   var imagesTable = DS.Tables["Images"];
   var imagesRows = imagesTable.Rows;
   var count = imagesRows.Count;

   if (count <= 0)
      return;

   var imageColumnValue = imagesRows[count - 1]["Image"];

   if (imageColumnValue == DBNull.Value)
      return;

   var data = (Byte[])imageColumnValue;

   using (var stream = new MemoryStream(data))
   {
       pictureBox1.Image = Image.FromStream(stream);
   }

But the image it displays is not stretched even I set the BackgroundImageLayout to stretch

I also tried this:

using (var stream = new MemoryStream(data))
{
    pictureBox1.Image = Image.FromStream(stream);
    pictureBox1.BackgroundImageLayout = ImageLayout.Stretch; 
}

Upvotes: 1

Views: 282

Answers (1)

King King
King King

Reputation: 63387

Your problem is you are mixed up between PictureBox.Image and PictureBox.BackgroundImage, so your code should be one of the followings:

using (var stream = new MemoryStream(data))
{
  pictureBox1.BackgroundImage = Image.FromStream(stream);
  pictureBox1.BackgroundImageLayout = ImageLayout.Stretch; 
}

//or

using (var stream = new MemoryStream(data))
{
  pictureBox1.Image = Image.FromStream(stream);
  pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage; 
}

Upvotes: 1

Related Questions