Wednesday, February 18, 2009

Load an image from Database with VB.Net

    Dim count As Integer = 1
    Dim Album As New Collection
    Dim Query As String
    Dim Archive As SqlConnection

Private Sub Form2_Load(ByVal sender As System.Object,ByVal e As System.EventArgs) Handles MyBase.Load
    Archive = New SqlConnection
    Archive.ConnectionString = "connection string"
    Query = "SELECT Photo FROM ALBUM"
    Dim cmd As New SqlCommand(Query, Archive)
    Archive.Open()
    Dim I As Integer = 0
    Dim reader As SqlDataReader = cmd.ExecuteReader()
    Dim Temp As Byte ()
    While reader.Read
        Temp = reader(0)
        Album.Add(Temp)
    End While
    If Album.Count > 0 Then
        Temp = CType (Album.Item(count), Byte())
        Dim Img As MemoryStream = New MemoryStream(Temp)
        PictureBox1.Image = Image.FromStream(Img)
    End If
End Sub

Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrev.Click
    Dim Temp As Byte ()
    If count > 1 Then
        count = count - 1
        Temp = CType (Album.Item(count), Byte())
        Dim Img As MemoryStream = New MemoryStream(Temp)
        PictureBox1.Image = Image.FromStream(Img)
    End If
End Sub

Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
    Dim Temp As Byte ()
    If count Album.Count Then
        count = count + 1
        Temp = CType (Album.Item(count), Byte())
        Dim Img As MemoryStream = New MemoryStream(Temp)
        PictureBox1.Image = Image.FromStream(Img)
    End If
End Sub

No comments: