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.LoadSets up the sample by filling a
DataTablewithin aDataSetwith the Employees table from the Northwind sample database. The EmployeeID, LastName, and FirstName fields are bound toTextBoxcontrols. TheBindingManagerBaseis obtained for the Employees table in theDataSet, a handler is attached to manage thePositionChangedevent, and that handler is called to position the display on the first record.BindingManagerBase.PositionChangedUpdates the
PictureBoxwith the image for the current record. This event is raised when thePositionproperty value changes.The EmployeeID for the current record is obtained using the position information in the
BindingManagerBaseobject. AConnectionobject andCommandobject are created and used to retrieve the Photo binary field for the employee record into aBytearray. AMemoryStreamobject is created from theBytearray. The staticFromStream( )method of theSystem.Drawing.Imageclass is used to load the image into thePictureBoxfrom theMemoryStream.- Move First
Button.Click Sets the current record of the bound controls to the first record by setting the
Positionproperty of theBindingManagerBaseobject to 0.- Move Previous
Button.Click Sets ...
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