使用vb.net在数据网格中显示数据库中的图像

时间:2016-02-02 15:25:10

标签: vb.net image winforms datagridview

我使用带有2个字段的MySql数据库:档案号和我保存图像名称和位置的字段。我想在我的winform上放置一个datagrid并在第一个单元格中显示一个图像(缩略图),在第二个单元格中显示一个dossiernumber,但是不能让它工作。

图片不显示并只留下缺失的图片链接。我也无法将图片放在第一个单元格中。这就是它的样子:

enter image description here

有什么问题?

这是我写的代码:

Imports MySql.Data.MySqlClient

Public Class Form1


    'ALLES OM DATAGRID TE PLAATSEN

    'GLOBALE DECLARATIES
    Dim conString As String = "server=localhost;userid=root;database=testvehicle"
    Dim con As New MySqlConnection(conString)
    Dim cmd As MySqlCommand
    Dim adapter As MySqlDataAdapter
    Dim dt As New DataTable()


    Private Sub Form1_GotFocus(sender As Object, e As EventArgs) Handles Me.GotFocus
        retrieve()
    End Sub



    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataGridView1.ColumnCount = 2
        DataGridView1.Width = 410
        'CONSTRUCT IMAGE COLUMN
        Dim imgCol As DataGridViewImageColumn = New DataGridViewImageColumn()
        DataGridView1.Columns(0).Name = "Image"
        DataGridView1.Columns.Add(imgCol)
            'CONSTRUCT DATA COLUMNS
        DataGridView1.Columns(1).Name = "dossiernr"
        DataGridView1.Columns(1).Width = 100
        DataGridView1.SelectionMode = DataGridViewSelectionMode.FullColumnSelect
    End Sub

    'ALLES OM DATAGRID TE VULLEN

    'PROCEDURE POPULATE ROW
    Private Sub populate(foto1 As String, product_dossiernr As String)
        Dim row As String() = New String() {foto1, product_dossiernr}
        'ADD ROW TO ROWS
        DataGridView1.Rows.Add(row)
    End Sub

'DATA ONTVANGEN

    Private Sub retrieve()
        DataGridView1.Rows.Clear()
        'SQL STATEMENT
        Dim sql As String = "SELECT foto1, product_dossiernr FROM producten ORDER BY product_dossiernr"
        cmd = New MySqlCommand(sql, con)
        'OPEN CON, RETRIEVE, FILL DATAGRID
        Try
            con.Open()
            adapter = New MySqlDataAdapter(cmd)
            adapter.Fill(dt)
            For Each row In dt.Rows
                populate(row(0), row(1))
            Next
            con.Close()
            dt.Rows.Clear()
        Catch ex As Exception
            MsgBox(ex.Message)
            con.Close()
        End Try
    End Sub

'EINDE DATAGRID VULLEN

End Class

1 个答案:

答案 0 :(得分:0)

在您的代码中,您将列命名为图像名称,而不是为其指定图片值,因此这就是您获取名称而不是图像的原因。

这是我以前用过的代码片段,效果非常好。

Dim ColImage As New DataGridViewImageColumn
Dim Img As New DataGridViewImageCell

'Set Name
ColImage.Name = "ColImg"

'Set Header text
ColImage.HeaderText = "Your Image!"

'Add column to datagridview
DataGridView1.Columns.Add(ColImage)

'Set image value
Img.Value = Image.FromFile("C:\YourImage.png")

'Add the image cell to a row
DataGridView1.Rows(0).Cells.Add(Img)