Saturday, 2 June 2012

Retrieve an Image from SQL Server in Picture Box Using VB.Net

Hi, There
Retrieving an image from sql server database is so simple just do following steps
  • Make a project and database which i mention in my Blog Take a look 
  • Add a picture box on your form, and a button for show image
  • On Show Button Click event paste following code
 If TextBox1.Text = "" Then
            MsgBox("plz enter roll no")
            Dim con As New SqlConnection("initial catalog=bsw;data source=.;integrated security=true")
            Dim com As New SqlCommand()
                PictureBox1.BackgroundImageLayout = ImageLayout.Stretch
                com.Connection = con
                com.CommandText = "select * from stu where roll=" & TextBox1.Text
                Dim dr As SqlDataReader = com.ExecuteReader()
                If dr.HasRows Then
                    Dim bits As Byte() = CType(dr("img"), Byte())
                    Dim memo As New MemoryStream(bits)
                    Dim myimg As New Bitmap(memo)
                    PictureBox1.Image = myimg

                    MsgBox("Record not found")
                End If

            Catch ex As Exception
            End Try
        End If
    End Sub