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")
            TextBox1.Focus()
        Else
            Dim con As New SqlConnection("initial catalog=bsw;data source=.;integrated security=true")
            Dim com As New SqlCommand()
            Try
                PictureBox1.BackgroundImageLayout = ImageLayout.Stretch
                com.Connection = con
                con.Open()
                com.CommandText = "select * from stu where roll=" & TextBox1.Text
                Dim dr As SqlDataReader = com.ExecuteReader()
                dr.Read()
                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

                Else
                    MsgBox("Record not found")
                End If

            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
           
        End If
    End Sub

2 comments:

  1. Thanks for the code.

    ReplyDelete
  2. Thanks!! It really helped me in my database project

    ReplyDelete