如何在VB中从Access数据库显示/获取图像到PictureBox

时间:2014-09-20 14:32:05

标签: vb.net vba visual-studio-2013

Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    GetPicture()
End Sub


Public Sub GetPicture()

    con.Open()

    Dim dt As New DataTable("Users")
    Dim rs As New OleDb.OleDbDataAdapter("Select * from Users where StudentNumber='" & TextBox1.Text & "' ", con)
    rs.Fill(dt)
    DataGridView1.DataSource = dt
    DataGridView1.Refresh()
    Label1.Text = dt.Rows.Count
    rs.Dispose()
    con.Close()

    If Val(Label1.Text) = 1 Then
        Dim i As Integer
        i = DataGridView1.CurrentRow.Index
        PictureBox1.Image = FixNull(DataGridView1.Item(6, i).Value)


    End If
______________________________

我在这行上遇到了这个错误:PictureBox1.Image = FixNull(DataGridView1.Item(6,i).Value)

-> Unable to cast object of type 'System.Byte[]' to type 'System.Drawing.Image'.


截图:

1 个答案:

答案 0 :(得分:0)

我只是想通了,这是解决方案


公共类表单

Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\UsersDB.accdb")
Dim cmd As New OleDbCommand("", con)
Dim Reader As OleDb.OleDbDataReader
Dim cn As New OleDbConnection
Dim i As Integer

Public Sub GetData()

    con.Open()
    Dim dt As New DataTable("Users")
    Dim rs As New OleDb.OleDbDataAdapter("Select * from Users where StudentNumber='" & TextBox1.Text & "' ", con)
    rs.Fill(dt)
    DataGridView1.DataSource = dt
    DataGridView1.Refresh()
    Label1.Text = dt.Rows.Count
    rs.Dispose()
    con.Close()

    If Val(Label1.Text) = 1 Then
        Dim i As Integer
        i = DataGridView1.CurrentRow.Index
        'Image
        Dim bytes As [Byte]() = (DataGridView1.Item(6, i).Value)
        Dim ms As New MemoryStream(bytes)
        PictureBox1.Image = Image.FromStream(ms)

    End If

End Sub

结束班