VB.net - insert/retrieve picture from mysql Database directly to/from a Picturebox

后端 未结 5 1728
逝去的感伤
逝去的感伤 2020-12-21 08:50

I\'m am having a heck of a time finding a code snippet that works for this. I have got to the point where it appears the picture is stored as a blob (perhaps incorrectly) by

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 09:25

    I just wrote this code as part of my contribution to this forum though not a member but love to help. This code search for multiple records and their corresponding images as you keep searching for record instead of search for one record and close the app to search again. This code allows you to search a record, clear the fields enter the search criteria and search again & again.

        If TextBox3.Text = "" Then ' This is the search field to be used it could be any field from your database that will match the value from the database. Either firstname, phone or email etc
            MsgBox("Nothing to search for from the database", MsgBoxStyle.OkOnly + MsgBoxStyle.Exclamation, "Oop!")
        End If
        Try
            conn.Open()
            Dim data As New MySqlDataAdapter("SELECT * FROM users_data WHERE phoneno = '" & TextBox3.Text & "' ", conn)
    
            Dim dTable As New DataTable
            data.Fill(dTable)
    
            If dTable.Rows.Count > 0 Then
                TextBox1.Text = dTable.Rows(0).Item("firstname")
                TextBox2.Text = dTable.Rows(0).Item("lastname")
    
                'Fetching the corresponding image to this member
                Dim arrImage As Byte()
                Dim myMS As New IO.MemoryStream
                If Not IsDBNull(dTable.Rows(0).Item("myimage")) Then
                    arrImage = dTable.Rows(0).Item("myimage")
                    For Each ar As Byte In arrImage
                        myMS.WriteByte(ar)
                    Next
                    PictureBox1.Image = System.Drawing.Image.FromStream(myMS)
                End If
    
            Else
                MsgBox("No record found for this Phone No: " & TextBox3.Text & " Enter a valid Phone No or consult the Admin Manager", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Record not found")
                clear()
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        Finally
            conn.Close()
        End Try
    

    This code could work for MYSQL Server database and Microsoft SQL databases as well. The only difference is is changing this statement Dim data As New MySqlDataAdapter which is for MYSQL Server to Dim data As New SqlDataAdapter for Microsoft SQL server. Good evening all StackOverflowers

提交回复
热议问题