Visual Basic Code Snippet - Get Image from sql server
(VB) Visual Basic code snippet connects to SQL server and executes SQL statement and returns the Image data. ScalarToImage returns an Image using open database connection and SQL statement.
Bookmark:
Visual Basic Code Snippet - Get Image from sql server
This .Net Visual Basic code snippet connects to SQL server and executes SQL statement and returns the binary image data from database. To use this function simply provide open database connection and SQL statement. This function uses SqlClient name space to get data using SqlCommand. Modify the exception handling section to as your project requirements.
01 | Public Function ScalarToImage( ByRef _SqlConnection As System.Data.SqlClient.SqlConnection, ByVal _SQL As String ) As System.Drawing.Image |
02 | Dim _SqlRetVal As Object = Nothing |
03 | Dim _Image As System.Drawing.Image = Nothing |
08 | Dim _SqlCommand As New System.Data.SqlClient.SqlCommand(_SQL, _SqlConnection) |
10 | _SqlRetVal = _SqlCommand.ExecuteScalar() |
15 | Catch _Exception As Exception |
18 | Console.WriteLine(_Exception.Message) |
26 | Dim _ImageData(-1) As Byte |
27 | _ImageData = CType (_SqlRetVal, Byte ()) |
28 | Dim _MemoryStream As New System.IO.MemoryStream(_ImageData) |
29 | _Image = System.Drawing.Image.FromStream(_MemoryStream) |
30 | Catch _Exception As Exception |
33 | Console.WriteLine(_Exception.Message) |
Here is a simple example showing how to use above function (ScalarToImage) to connect to SQL database and get image data and show it in a picturebox.
02 | Dim _SqlConnection As New System.Data.SqlClient.SqlConnection() |
05 | _SqlConnection.ConnectionString = "Server=SERVERADDRESS;Database=DATABASENAME;Uid=USERID;Pwd=PASSWORD;" |
10 | Catch _Exception As Exception |
12 | Console.WriteLine(_Exception.Message) |
16 | If _SqlConnection IsNot Nothing AndAlso _SqlConnection.State = ConnectionState.Open Then |
20 | Dim _Image As System.Drawing.Image = ScalarToImage(_SqlConnection, "SELECT image FROM sampletable WHERE productid = 14" ) |
22 | If _Image IsNot Nothing Then |
24 | pictureBox1.Image = _Image |
27 | pictureBox1.Image = Nothing |
31 | _SqlConnection.Close(); |
VB Keywords Used:
- Byte
- CType
- Image
- MemoryStream
- FromStream
- ExecuteScalar
- SqlConnection
- ConnectionString
- SqlCommand
- Exception
Code Snippet Information:
- Applies To: .Net, VB, Visual Basic, CLI, SQL, SqlCommand, ExecuteScalar, MemoryStream, Image, SQL Server, SQL Client, Connection String, Database Connection, SQL Server Binary Data
- Programming Language : Visual Basic (VB)
External Resources: