将图像从datagridview显示到图片框

时间:2016-02-29 10:10:47

标签: vb.net datagridview

任何人都可以帮我这个吗?场景是当我点击datagridview中的任何列时,它会将图像显示到图片框

Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick

    If e.RowIndex >= 0 Then
        Dim row As DataGridViewRow
        row = Me.DataGridView1.Rows(e.RowIndex)

        lblProperty.Text = row.Cells("Column1").Value.ToString
        txtType.Text = row.Cells("Column2").Value.ToString
        txtPrice.Text = row.Cells("Column3").Value.ToString
        txtBed.Text = row.Cells("Column4").Value.ToString
        txtBath.Text = row.Cells("Column5").Value.ToString
        txtFootages.Text = row.Cells("Column6").Value.ToString
        txtStatus.Text = row.Cells("Column7").Value.ToString
        txtYear.Text = row.Cells("Column8").Value.ToString
        txtDesc.Text = row.Cells("Column9").Value.ToString

        Dim bytes As [Byte]() = row.Cells("Column10").Value
        Dim ms As New MemoryStream(bytes)
        pbImage.Image = Image.FromStream(ms)

        txtDate.Text = row.Cells("Column11").Value.ToString
        txtAddress.Text = row.Cells("Column12").Value.ToString
        txtStories.Text = row.Cells("Column13").Value.ToString

    End If
End Sub

它有一个错误无法转换类型为' System.String'的对象输入' System.Byte []'。

2 个答案:

答案 0 :(得分:0)

也许你在想它,有一个功能可以轻松绘制位图。

我建议使用ColumnBounds在DataGridView上使用DrawToBitmap 例如:

Dim GridBitmap as new Bitmap(DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false).width,DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false).height)
DataGridView1.DrawToBitmap(GridBitmap,DataGridView1.GetColumnDisplayRectangle(row.Cells("Column10").ColumnIndex,false))
pbImage.Image = GridBitmap

可能需要适应您的DataGridView。

注意,而不是:

    Dim bytes As [Byte]() = row.Cells("Column10").Value
    Dim ms As New MemoryStream(bytes)
    pbImage.Image = Image.FromStream(ms)

还有问题吗?试试这个:

新项目。
将DataGridView(DataGridView1)添加到表单中 在gridview中添加一些随机列 在表单中添加一个图片框(PictureBox1)
确保图片框属性“SizeMode”设置为自动大小 添加一个事件forDataGridView1.MouseDown 将此代码添加到活动中。

Dim GridBitmap As New Bitmap(DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Width + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Left, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Height)
Dim GridColRectangle As New Rectangle(0, 0, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Width + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Left, DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Height + DataGridView1.GetColumnDisplayRectangle(e.ColumnIndex, True).Top)
DataGridView1.DrawToBitmap(GridBitmap, GridColRectangle)
PictureBox1.Image = GridBitmap

您可能需要根据自己的应用进行调整。

答案 1 :(得分:-1)

context.sync()