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 the current record of the bound controls to the previous record by decrementing the Position property of the BindingManagerBase object by 1.

Move Next Button.Click

Sets the current record of the bound controls to the next record by incrementing the Position property of the BindingManagerBase object by 1.

Move Last Button.Click

Sets the current record of the bound controls to the last record by setting the Position property of the BindingManagerBase object to the total number of records, as returned by the Count property, minus 1.

The C# code is shown in Example 7-16.

Example 7-16. File: DisplayDatabaseImageForm.cs

// Namespaces, variables, and constants
using System;
using System.Configuration;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Data;
using System.Data.SqlClient;

private DataSet ds;
private SqlDataAdapter da;

private BindingManagerBase bm;

// . . . 

private void DisplayDatabaseImageForm_Load(object sender,
 System.EventArgs e)
{
 // Create the DataSet.
 ds = new DataSet( );

 // Create the DataAdapter and retrieve the Employees table.
 String selectCommand =
 "SELECT EmployeeID, LastName, FirstName FROM Employees";
 da = new SqlDataAdapter(selectCommand,
 ConfigurationSettings.AppSettings["Sql_ConnectString"]);
 da.FillSchema(ds, SchemaType.Source, "Employees");
 da.Fill(ds, "Employees");

 // Bind several table fields to controls.
 employeeIdTextBox.DataBindings.Add("Text", ds,
 "Employees.EmployeeID");
 lastNameTextBox.DataBindings.Add("Text", ds, "Employees.LastName");
 firstNameTextBox.DataBindings.Add("Text", ds, "Employees.FirstName");

 // Get the binding manager base for the Employees table.
 bm = BindingContext[ds, "Employees"];
 // Update the image in response to each record reposition.
 bm.PositionChanged += new EventHandler(bm_PositionChanged);
 // Update the display for the first record.
 bm_PositionChanged(null, null);
}

private void bm_PositionChanged(Object sender, EventArgs e)
{
 // Refresh the photo displayed when the current record changes.

 // Get the new EmployeeID using the BindingManager.
 int employeeId =
 (int)ds.Tables["Employees"].Rows[bm.Position]["EmployeeID"];

 // Create a connection.
 SqlConnection conn = new SqlConnection(
 ConfigurationSettings.AppSettings["Sql_ConnectString"]);
 // Create a command to retrieve the employee photo.
 String sqlText = "SELECT Photo FROM Employees WHERE EmployeeID=" +
 employeeId;
 SqlCommand cmd = new SqlCommand(sqlText, conn);

 // Retrieve the employee photo to a stream.
 conn.Open( );
 Byte[] image = (Byte[])cmd.ExecuteScalar( );;
 MemoryStream ms = new MemoryStream(image);
 conn.Close( );

 // Load the image into the PictureBox from the stream.
 photoPictureBox.Image = Image.FromStream(ms);
 ms.Close( );
}

private void moveFirstButton_Click(object sender, System.EventArgs e)
{
 bm.Position = 0;
}

private void movePreviousButton_Click(object sender, System.EventArgs e)
{
 bm.Position -= 1;
}

private void moveNextButton_Click(object sender, System.EventArgs e)
{
 bm.Position += 1;
}

private void moveLastButton_Click(object sender, System.EventArgs e)
{
 bm.Position = bm.Count - 1;

Discussion

The Windows Forms PictureBox control displays bitmap, JPEG, metafile, or icon images.

In the solution, the image stored as a BLOB in the database is retrieved into a Byte array, which is in turn copied into a System.IO.MemoryStream object. The static FromStream( ) method of the Image class creates an Image object that is loaded into the PictureBox .

This example uses the modified version of Northwind, where the Photo field has been updated for all employees to remove the OLE image header. For more information, see the online sample code.

Binding Windows Forms Controls

The abstract BindingManagerBase class synchronizes all Windows Forms controls (i.e., Binding objects) that are bound to the same data source so that they display information from the object within the data source, such as a row in a DataTable .

The BindingContext class is used to instantiate a BindingManagerBase object and either a CurrencyManager or PropertyManager object is returned depending on the type of data source:

  • The CurrencyManager class inherits from the BindingManagerBase class and maintains a pointer for the current item in a data source that implements IList , IListSource , or IBindingList . Data sources do not necessarily support a current-item pointer. The CurrencyManager notifies all data-bound controls if the current item changes so that they can refresh their data.
  • The PropertyManager class inherits from the BindingManagerBase class and maintains the current property of an object, rather than an object in a list.

The Position property is a zero-based index that gets or sets the current position in the underlying data source list. The Count property returns the number of items in the list. The Current property returns the current object in the list, which must be cast to the type of object in the underlying data source before it can be used.

Connecting to Data

Retrieving and Managing Data

Searching and Analyzing Data

Adding and Modifying Data

Copying and Transferring Data

Maintaining Database Integrity

Binding Data to .NET User Interfaces

Working with XML

Optimizing .NET Data Access

Enumerating and Maintaining Database Objects

Appendix A. Converting from C# to VB Syntax

show all menu



ADO. NET Cookbook
ADO.NET 3.5 Cookbook (Cookbooks (OReilly))
ISBN: 0596101406
EAN: 2147483647
Year: 2002
Pages: 222
Authors: Bill Hamilton
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net