从数据库中检索图像

时间:2013-01-29 06:29:22

标签: vb.net picturebox

我正在处理显示员工列表的项目。在这里,将显示员工的信息和图片。我的项目现在可以显示列表框中的员工列表,当我双击员工时,他/她的个人资料将显示在文本框中。我的问题是我不能让他们的照片显示在picturebox。我已将他们的图片与他们的ID,名称和个人资料一起存储在我的数据库中的表格上。 It only shows the picture of the first employee on the table。有人可以帮助我吗?

这就是我已经做过的事情:

我填充了列表框:

Call Connect() 
    With Me
        STRSQL = "Select employee_name from Employees"
        Try
            myCmd.Connection = myConn
            myCmd.CommandText = STRSQL
            reader = myCmd.ExecuteReader
            If (reader.Read()) Then
                reader.Close()
                adptr.SelectCommand = myCmd
                adptr.Fill(dt)
                lstEmployee.DisplayMember = "employee_name"
                lstEmployee.ValueMember = "employee_id"
                If dt.Rows.Count > 0 Then
                    For i As Integer = 0 To dt.Rows.Count - 1
                        lstEmployee.Items.Add(dt.Rows(i)("employee_name"))
                    Next
                End If
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End With

这是我在文本框中显示信息的方式

Dim FileSize As UInt32
    Dim mStream As New System.IO.MemoryStream()
    Dim arrImage() As Byte = mStream.GetBuffer()
    FileSize = mStream.Length
    Dim cmd As New MySqlCommandBuilder
    Call Connect()
    With Me
        STRSQL = "select employee_name, profile from Employees where employee_id = " & lstEmployee.SelectedIndex
        Try
            myCmd.Connection = myConn
            myCmd.CommandText = STRSQL
            reader = myCmd.ExecuteReader

            If (reader.Read()) Then
                txtName.Text = reader("employee_name")
                txtProfile.Text = reader("profile")
            End If
        Catch ex As Exception
            MsgBox(ex.Message)
        Finally
            myConn.Close()
        End Try
        adptr.SelectCommand = myCmd
        dt = New DataTable
        adptr = New MySqlDataAdapter("select picture from Employees", myConn)
        cmd = New MySqlCommandBuilder
        adptr.Fill(dt)
        Dim lb() As Byte = dt.Rows(0).Item("picture")
        Dim lstr As New System.IO.MemoryStream(lb)
        pix.Image = Image.FromStream(lstr)
        pix.SizeMode = PictureBoxSizeMode.StretchImage
        lstr.Close()

1 个答案:

答案 0 :(得分:1)

您错过了where clause必须要搜索一位员工才能查看该图片。

adptr = _
      New MySqlDataAdapter("select picture from Employees " + _
      "where employee_id = " & lstEmployee.SelectedIndex, myConn)
cmd = New MySqlCommandBuilder
adptr.Fill(dt)
Dim lb() As Byte = dt.Rows(0).Item("picture")
Dim lstr As New System.IO.MemoryStream(lb)
pix.Image = Image.FromStream(lstr)
pix.SizeMode = PictureBoxSizeMode.StretchImage
lstr.Close()

P.S。:您必须研究LINQ (Language-Integrated Query)以获得更好的方法。