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 aDataSet
with the Employees table from the Northwind sample database. The EmployeeID, LastName, and FirstName fields are bound toTextBox
controls. TheBindingManagerBase
is obtained for the Employees table in theDataSet
, a handler is attached to manage thePositionChanged
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 thePosition
property value changes.The EmployeeID for the current record is obtained using the position information in the
BindingManagerBase
object. AConnection
object andCommand
object are created and used to retrieve the Photo binary field for the employee record into aByte
array. AMemoryStream
object is created from theByte
array. The staticFromStream( )
method of theSystem.Drawing.Image
class is used to load the image into thePictureBox
from theMemoryStream
.- Move First
Button.Click
Sets the current record of the bound controls to the first record by setting the
Position
property of theBindingManagerBase
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.