VB.NET retrieving varbinary data into picture box - sql

I have a some data in SQL Server in a VARBINARY column, I just want to know how to display it into a PictureBox in VB.NET. How to do this?
Binary data looks something like:
0x1F8B0800000000000400EDBD07601C499625262F6DCA7B7F4AF54AD7E.....(and a great many more bytes to come)......

Private Sub sample()
Dim command, commandReader As New NpgsqlCommand
command.Connection = GetConnection()
command.CommandText = "select imgField from imgtable"
Dim productImageByte As Byte() = TryCast(command.ExecuteScalar, Byte())
If productImageByte IsNot Nothing Then
Using productImageStream As Stream = New System.IO.MemoryStream(productImageByte)
PPicBoxPhoto.Image = Image.FromStream(productImageStream)
End Using
End If
End Sub
NOTE : This a sample of my code that I'm using for my requirement, using PostgreSQL database and the image data type is bytea

Related

How we can get a data table raw data into a Single type Array variable?

How we can get a data table raw data into a Single type Array variable?
Like;
Dim price_range1() As Single = {10.4, 9.6, 6.8, 5.6, 4.4}
Dim price_range2() As Single = {5.2, 4.8, 3.4, 2.8, 2.2}
Dim price_range3() As Single = {2.6, 2.4, 1.7, 1.4, 1.1}
I'm already getting all data into the DataGrid. But I need to get those raw data as a variable.
DataGridView Table
Like that kind of variables
Imports MySql.Data.MySqlClient
Public Class showitems
Public commmand As New MySqlCommand
Public adapter As New MySqlDataAdapter
Public datatable As New DataTable
Private Sub showitems_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim var As New ArrayList
If Db_conn() = True Then
Dim sql As String
sql = "SELECT id, range1,range2,range3,range4,range5 FROM `pioltprice` WHERE id = 5 OR id = 6 OR id = 7 "
command.CommandText = sql
command.Connection = conn
adapter.SelectCommand = command
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
Else
MsgBox("Error occurred")
End If
End Sub
End Class
Use MySql DataTable, MySql DataAdapter
You will need to take the values and include them in your array.
If you want to reuse the DataTable that you're already filling, then you could do the following after adapter.Fill(datatable):
Get the Row by its index
Get the ItemArray of the selected DataRow
Skip the first cell in the ItemArray (which is the Id)
Convert the values to a Single
Dim price_range1() As Single
If (datatable.Rows().Count > 0) Then
price_range1 = datatable.Rows().Item(0).ItemArray().Skip(1).Select(Function(cell) Single.Parse(cell)).ToArray()
End If
Dim price_range2() As Single
If (datatable.Rows().Count > 1) Then
price_range2 = datatable.Rows().Item(1).ItemArray().Skip(1).Select(Function(cell) Single.Parse(cell)).ToArray()
End If
Dim price_range3() As Single
If (datatable.Rows().Count > 2) Then
price_range3 = datatable.Rows().Item(2).ItemArray().Skip(1).Select(Function(cell) Single.Parse(cell)).ToArray()
End If
Live Demo: https://dotnetfiddle.net/pdEAkz

Check if image column is Null VB.NET

Good Day everyone. I need help with my code below.
Dim stream As New MemoryStream()
connect()
Dim command As New SqlCommand("SELECT image FROM tblHouseholdMembers WHERE id= '" & lvmem.FocusedItem.Text & "'", cn)
Dim image As Byte() = DirectCast(command.ExecuteScalar(), Byte()) --> 'Error message of null image
stream.Write(image, 0, image.Length)
cn.Close()
Dim bitmap As New Bitmap(stream)
pbProfilePic.Image = bitmap
I want to put a messagebox to identify if it's null before the error cast.
Instead of using the DirectCast method, use the TryCast and then check if the casting result is nothing:
Dim image As Byte() = TryCast(command.ExecuteScalar(), Byte())
if image isnot nothing then
stream.Write(image, 0, image.Length)
cn.Close()
Dim bitmap As New Bitmap(stream)
pbProfilePic.Image = bitmap
else
'Error message here
end if
The way to directly test if a field coming back from a database is null is:
if ValueFromDb is System.DbNull.Value then
' whatever you want to do in that case
Something that really confused me when I was first learning VB is that a null value from a DB read is NOT equal to Nothing. It is not Nothing, it is System.DbNull.Value.
Most of my projects these days, I write a little function I call "denull" that says something like:
public shared function denull(value as object, defalt as object)
if value is system.dbnull.value then
return defalt
else
return value
end function
Then I wrap every value I read from the db in this function. This saves a lot of code.
for each row in mydataset.tables(0).rows
foo=denull(row("foo"),"")
bar=denull(row("bar"),0)
plugh=denull(row("plugh"),nothing)
... etc ...

Loop through each row, create button for each record. Cannot get image from database

I have a form that I am trying to populate with a control for each item on my database (SQLCe). Problem is that one of the items I am trying to return from the database is an image. However, my original code gave me an error:
Value of type "Byte' cannot be converted to 'System.Drawing.Image'
Here is my original code
Private Sub btnCategories_Click(sender As Object, e As EventArgs) Handles btnCategories.Click
Dim dt As DataTable = ProducT_CATEGORYTableAdapter.GetData
For Each row As DataRow In dt.Rows
Dim btn As New btnCategoryTabs()
btn.lblCategoryName.Name = DirectCast(row("Category_Name"), String)
btn.lblCategoryName.Text = btn.lblCategoryName.Name
btn.picPCategoryPicture.Image = DirectCast(row("Image"), Byte) 'Error Here'
'Add categories to the Panel
flpMainPanel.Controls.Add(btn)
Next
End Sub
I am sure that I have to convert the image, so I started messing around with this bit of code:
Dim Stream As New MemoryStream()
Dim image As Byte() = CType('Can't figure out what to put here), Byte())
Stream.Write(image, 0, image.Length)
Dim bitmap As New Bitmap(Stream)
Any help will be appreciated.
Thanks.
If you have stored image data in your database then it would be a Byte() i.e. and array, not just a single Byte. You then have to convert that Byte array to an Image. You're on the right track. Here's one I prepared earlier:
Dim connection As New SqlConnection("connection string here")
Dim command As New SqlCommand("SELECT Picture FROM MyTable WHERE ID = 1", connection)
connection.Open()
Dim pictureData As Byte() = DirectCast(command.ExecuteScalar(), Byte())
connection.Close()
Dim picture As Image = Nothing
'Create a stream in memory containing the bytes that comprise the image.'
Using stream As New IO.MemoryStream(pictureData)
'Read the stream and create an Image object from the data.'
picture = Image.FromStream(stream)
End Using
http://www.vbforums.com/showthread.php?469562-Saving-Images-in-Databases&highlight=
In your case specifically, that becomes:
'Create a stream in memory containing the bytes that comprise the image.'
Using stream As New IO.MemoryStream(DirectCast(row("Image"), Byte()))
'Read the stream and create an Image object from the data.'
btn.picPCategoryPicture.Image = Image.FromStream(stream)
End Using

How to read returned stream data

I am currently reading a stream like this:
wc = New System.Net.WebClient()
strm = wc.OpenRead(url)
Data.ReadXml(strm, XmlReadMode.InferSchema)
strm.Close()
Besides the Dataset reading the stream I would also like to be able to output the text to the log file. Or for testing to a debug.print statement.
How can I do that? I have tried adding a new stream reader after the wc.openread but then there is no data for the dataset to read.
Any help would be appreciated..
Rick
after the
Data.ReadXml(strm, XmlReadMode.InferSchema)
call the Data.GetXml
Dim xmlString As String = Data.GetXml
Sample below,
Dim Data As New DataSet
Using wc = New System.Net.WebClient()
Using strm = wc.OpenRead("http://news.yahoo.com/rss/entertainment")
Data.ReadXml(strm, XmlReadMode.InferSchema)
Dim xmlString As String = Data.GetXml
Debug.WriteLine(xmlString)
End Using
End Using

how to update image using database in vb.net

what is the problem of this code?? i got a error for the GDI+ and i dont know to solve.
Private Sub saveEmployee()
Dim ms As New MemoryStream
PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)--i got error in this line..A generic error occurred in GDI+.
Dim arrPic() As Byte = ms.GetBuffer()
Dim cmdEmp As New MySqlCommand
Dim sqlEmp As String
sqlEmp = "update tbl_employee set emPic=#emPic where emID='" & lbl_empID.Text & "'"
With cmdEmp
.Parameters.AddWithValue("#emPic", arrPic)
.ExecuteNonQuery()
End With
End Sub
Try replacing that line with this :
Dim bm as Bitmap = new Bitmap(PictureBox1.Image)
bm.Save(ms, PictureBox1.Image.RawFormat)
The reason could be that the Image is being used by the PictureBox. Its also good practice to have the following instead :
Using ms As MemoryStream = New MemoryStream()
Dim bm as Bitmap = new Bitmap(PictureBox1.Image)
bm.Save(ms, PictureBox1.Image.RawFormat)
Dim arrPic() As Byte = ms.GetBuffer()
Dim cmdEmp As New MySqlCommand
Dim sqlEmp As String
sqlEmp = "update tbl_employee set emPic=#emPic where emID=#emID"
With cmdEmp
.Parameters.AddWithValue("#emPic", arrPic)
.Parameters.AddWithValue("#emID", int.Parse(lbl_empID.Text))
.ExecuteNonQuery()
End With
End Using
This way the MemoryStream will get Disposed after being used. And adding #emID as a parameter is safer.
RESOLVED!!!
Bind picture box to the datasource field using the Advance tab in the DataBindings section. Use the ImageLocation property instead of image. Then change the Update mode to NEVER. but how abt the update ??? Use a textbox and hide behind the Picture box [with visible = true]. Bind textbox to same datasource. THAT IS!!!
image displays directly in picture box whilst the textbox TextChanged property handles whether there is UPDATE or Not. took me a while but it works fine now. good luck as u code... ~ SAM, GHANA