8.18. Displaying an Image from a Database in a Windows Forms Control
Problem
You need to display an image from a database in a Windows Forms control.
Solution
Read the image into a byte array and load it directly into a PictureBox control using a MemoryStream.
Follow these steps:
Create a C# Windows Forms application,
LoadImageIntoWindowsFormControl.Add the following control to the
Form1design surface:PictureBoxnamedproductPhotoPictureBox
The completed layout of the Windows Form named
Form1is shown in Figure 8-35.

Figure 8-35. Layout for Form1 in LoadImageIntoWindowsFormControl solution
The C# code in Form1.cs in the project LoadImageIntoWindowsFormControl is shown in Example 8-30. The solution retrieves the LargePhoto binary field from the Production.ProductPhoto table in AdventureWorks for ProductPhotoID = 100 into a byte array. A MemoryStream object is created from the byte array. The static FromStream() method of the System.Drawing.Image class is used to load the image into the PictureBox from the MemoryStream.
Example 8-30. File: Form1.cs for LoadImageIntoWindowsFormControl solution
using System; using System.Data; using System.Data.SqlClient; using System.IO; using System.Windows.Forms; using System.Drawing; namespace LoadImageIntoWindowsFormControl { public partial class Form1 : Form { public Form1() { InitializeComponent(); productPhotoPictureBox.SizeMode = PictureBoxSizeMode.AutoSize; ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access