Use CurrencyManager and MemoryStream to Display Images


This article and attached sample code demonstrates you how to use the CurrencyManager and MemoryStream to display images. The current demonstration displays all the records of the employees with their company and the personal Information.

To bind the textboxes with the appropriate fields in the datbase table use the

elementname.Databindings.add( property , Datasource , Datamember)

To bind the respective textboxes /comboboxes with fields the code goes as below:

lblEmpID.DataBindings.Add("text", ds.Tables(0), "Employeeid")
txtFirstName.DataBindings.Add("text", ds.Tables(0), "FirstName")
txtLastName.DataBindings.Add("text", ds.Tables(0), "LastName")
txtCountry1.DataBindings.Add("text", ds.Tables(0), "Country")
....

The CurrencyManager is used to keep data-bound controls synchronized with each other (showing data from the same record). This is done by managing a collection of the bound data supplied by a data source. After binding the data the currencyManager is assigned to:

mycurmgr = CType(Me.BindingContext(ds.Tables(0)), CurrencyManager)

To navigate through the records the important property of the currencyManager is its position

Depending on the position its given as

mycurmgr.Position = 0 'First Record
mycurmgr.Position = mycurmgr.Position -1 'Previous Record
mycurmgr.Position = mycurmgr.Position -1 'Next Record
mycurmgr.Position = mycurmgr.count 'Last Record

To display the images from the database in the Picturebox Control use MemoryStream(System.IO namespace)

myconnection.Open()
Dim mycommand As New SqlCommand("Select photo from Employees where Employeeid =" & CInt(lblEmpID.Text), myconnection)
Dim strsql As String = "Select photo from Employees where Employeeid =" & CInt(lblEmpID.Text)
Dim img As Byte() = mycommand.ExecuteScalar
Dim offset As Integer = 78
Dim ms As New MemoryStream()
ms.Write(img, offset, img.Length - offset)
Dim bmp As New Bitmap(ms)
bmp.Save("sample.gif", System.Drawing.Imaging.ImageFormat.Gif)
PictureBox1.Image = bmp


Similar Articles