7.8. 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 with a MemoryStream.

The sample code contains six event handlers:

Form.Load

Sets up the sample by filling a DataTable within a DataSet with the Employees table from the Northwind sample database. The EmployeeID, LastName, and FirstName fields are bound to TextBox controls. The BindingManagerBase is obtained for the Employees table in the DataSet, a handler is attached to manage the PositionChanged event, and that handler is called to position the display on the first record.

BindingManagerBase.PositionChanged

Updates the PictureBox with the image for the current record. This event is raised when the Position property value changes.

The EmployeeID for the current record is obtained using the position information in the BindingManagerBase object. A Connection object and Command object are created and used to retrieve the Photo binary field for the employee record 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.

Move First Button.Click

Sets the current record of the bound controls to the first record by setting the Position property of the BindingManagerBase object to 0.

Move Previous Button.Click

Sets ...

Get ADO.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.