O'Reilly logo

ADO.NET Cookbook by Bill Hamilton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required