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