Displaying an Image from a Database in a Windows Forms Control
lượt xem 12
download
[ Team LiB ] Recipe 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.
Bình luận(0) Đăng nhập để gửi bình luận!
Nội dung Text: Displaying an Image from a Database in a Windows Forms Control
- [ Team LiB ] Recipe 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 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. [ Team LiB ]
CÓ THỂ BẠN MUỐN DOWNLOAD
-
Binding a Group of Radio Buttons in a Windows Form
6 p | 116 | 13
-
Dynamically Creating Crystal Reports
3 p | 96 | 13
-
Displaying an Image from a Database in a Web Forms Control
3 p | 95 | 12
-
Returning an Output Parameter Using a DataReader
4 p | 96 | 11
-
Using a DataView to Control Edits, Deletions, or Additions in Windows Forms
3 p | 96 | 10
-
Retrieving Stored Procedure Return Values Using a DataReader
4 p | 92 | 9
-
Using ADO.NET Design-Time Features in Classes Without a GUI
4 p | 90 | 8
-
Specifying Locking Hints in a SQL Server Database
5 p | 89 | 8
-
Loading a Windows PictureBox with Images Stored by Access as OLE Objects
5 p | 116 | 8
-
Retrieving Data from an Oracle Package
5 p | 91 | 7
-
Using Transaction Isolation Levels to Protect Data
5 p | 80 | 7
-
Adding Search Capabilities to Windows Forms
3 p | 96 | 7
-
Resolving Data Conflicts
8 p | 90 | 7
-
Retrieving Update Errors
5 p | 64 | 7
-
Replacing Null Values in a Strongly Typed DataSet
4 p | 96 | 6
-
Retrieving Hierarchical Data into a DataSet
4 p | 77 | 6
-
Checking for Concurrency Violations
7 p | 75 | 5
Chịu trách nhiệm nội dung:
Nguyễn Công Hà - Giám đốc Công ty TNHH TÀI LIỆU TRỰC TUYẾN VI NA
LIÊN HỆ
Địa chỉ: P402, 54A Nơ Trang Long, Phường 14, Q.Bình Thạnh, TP.HCM
Hotline: 093 303 0098
Email: support@tailieu.vn