none
How send picture column from datagridview form1 to picturebox form2 RRS feed

  • Question

  • Please help

    I would like to pass data from datagridview form1 to form2, what will happen is that when the datagridview selected row will be double clicked form 2 will be opened and will send textbox1 will be firstname, textbox2 will be lastname, textbox3 will be timestamp, textbox4 will be captured datatime and then picture will be sent to picture box. I was able to successfully password the data from textboxes but not on the picturebox

    This will be my codes on form1

    Private Sub DataGridView1_DoubleClick(sender As Object, e As EventArgs) Handles DataGridView1.DoubleClick
            If DataGridView1.SelectedRows.Count > 0 Then
                For Each frm As Form In Application.OpenForms
                    If TypeOf frm Is frmUpdateAttendance Then
                        frm.Activate()
                        Return
                    End If
                Next

                Dim fm As New frmUpdateAttendance
                fm.txtFirstname.Tag = DataGridView1.Item(0, DataGridView1.CurrentRow.Index).Value
                fm.MdiParent = frmMDI
                fm.Show()
                fm = Nothing
            End If
        End Sub

        Private Sub Load_Data()
            txtSearch.Text.Trim()

            Command = New OleDbCommand
            Adapter = New OleDbDataAdapter
            DTable = New DataTable

            Connection = New OleDbConnection(StrCon)
            With Connection
                If .State = ConnectionState.Closed Then
                    .ConnectionString = StrCon
                    .Open()
                End If
            End With

            Command.Connection = Connection
            Command.CommandType = CommandType.Text
            sql = " SELECT AttID, fname, lname, srno, datetime, capturedpic FROM  Attendance WHERE fname + ', ' + lname LIKE '%%" & txtSearch.Text &
                   "%%' OR fname + ' ' + lname = '" & txtSearch.Text & "'"
            Command.CommandText = sql
            Adapter.SelectCommand = Command
            Adapter.Fill(DTable)
            DataGridView1.DataSource = DTable

            If DTable.Rows.Count = 0 Then
                MsgBox("Information being searched was not found in database ..." + vbNewLine + vbNewLine & txtSearch.Text, MsgBoxStyle.Information, "Try again")
            End If
            Connection.Close()
        End Sub

    Form2

    Codes for the form2 to receive the textboxes and picture

        Private Sub Load_Data()

            Command = New OleDbCommand
            Connection = New OleDbConnection(StrCon)

            With Connection
                If .State = ConnectionState.Closed Then
                    .ConnectionString = StrCon
                    .Open()
                End If
            End With

            With Command
                .Connection = Connection
                .CommandType = CommandType.Text
                .CommandText = " SELECT AttID, fname, lname, srno, datetime, capturedpic " &
                               " FROM Attendance WHERE AttID = " & txtFirstname.Tag
            End With

            Reader = Command.ExecuteReader
            If Reader.HasRows Then
                While Reader.Read
                    txtFirstname.Text = Reader("AttID")
                    txtFirstname.Text = IIf(Not IsDBNull(Reader("fname")), Reader("fname"), "")
                    txtLastname.Text = IIf(Not IsDBNull(Reader("lname")), Reader("lname"), "")
                    txtTimeStamp.Text = IIf(Not IsDBNull(Reader("srno")), Reader("srno"), "")
                    txtDateTime.Text = IIf(Not IsDBNull(Reader("datetime")), Reader("datetime"), "")
                End While
            End If
            Reader.Close()
            Connection.Close()
        End Sub

    Friday, October 4, 2019 2:06 AM

Answers

  • Finally got it I added this chunk of code

     Dim bytImage() As Byte
                    bytImage = CType(Reader(5), Byte())
                    Dim ms As New MemoryStream(bytImage)
                    Dim bmImage As New Bitmap(ms)
                        ms.Close()
                    PictureBox1.Image = bmImage
                    PictureBox1.Refresh()

    • Marked as answer by jepoyman Sunday, October 13, 2019 12:05 PM
    Sunday, October 13, 2019 12:05 PM

All replies

  • Hi,
    try the following demo.

    Imports System.Drawing.Imaging
    Imports System.IO
    
    ''' <summary>
    ''' First Form
    ''' </summary>
    Public Class Form51
    
      Private dgv As New DataGridView With {.Dock = DockStyle.Fill, .AutoGenerateColumns = False}
    
      Private Sub Form51_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' simulate designer
        Me.Controls.Add(dgv)
        ' Columns in DataGrid
        Me.dgv.Columns.Add(New DataGridViewTextBoxColumn() With {.HeaderText = "name", .DataPropertyName = "Name"})
        Me.dgv.DataSource = Form51Modul.GetData
        ' Show second Form
        Call (New Form51a).Show()
      End Sub
    
    End Class
    
    ''' <summary>
    ''' static class (module) to get loaded data
    ''' </summary>
    Public Module Form51Modul
    
      Private _bs As BindingSource
    
      ''' <summary>
      ''' Get Source for binding
      ''' </summary>
      ''' <returns>BindingSource (DataView + CurrencyManager)</returns>
      Public Function GetData() As BindingSource
        If _bs Is Nothing Then
          _bs = New BindingSource
          _bs.DataSource = LoadDataTable()
        End If
        Return _bs
      End Function
    
      ''' <summary>
      ''' Load data from database,
      ''' here for simulation generate data on the fly
      ''' </summary>
      ''' <returns></returns>
      Private Function LoadDataTable() As DataTable
        Dim dt As New DataTable
        With dt
          With .Columns
            With .Add("ID", GetType(Integer))
              .AutoIncrement = True
              .AutoIncrementSeed = -1
              .AutoIncrementStep = -1
            End With
            .Add("Name", GetType(String))
            .Add("Picture", GetType(Byte()))
          End With
          For i = 1 To 10
            Dim dr = .NewRow
            dr("name") = $"Name {i}"
            ' generate picture
            Dim bmp As New Bitmap(200, 200)
            Dim gr = Graphics.FromImage(bmp)
            gr.DrawString($"Picture {i}", New Font("Arial", 30), Brushes.Red, New PointF(20, 20))
            Dim ms As New MemoryStream
            bmp.Save(ms, ImageFormat.Jpeg)
            dr("Picture") = ms.GetBuffer
            .Rows.Add(dr)
          Next
        End With
        Return dt
      End Function
    End Module
    
    ''' <summary>
    ''' Second Form
    ''' </summary>
    Public Class Form51a
      Inherits Form
    
      Private tbName As New TextBox With {.Dock = DockStyle.Top}
      Private pict As New PictureBox With {.Dock = DockStyle.Fill}
    
      Private Sub Form51a_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ' get source for binding
        Dim bs = Form51Modul.GetData
        ' simulate designer
        Me.Controls.AddRange(New Control() {tbName, pict})
        Me.tbName.DataBindings.Add("Text", bs, "Name")
        ' Handler to detect change the current row
        AddHandler bs.CurrentChanged, AddressOf LoadPicture
        LoadPicture(bs, Nothing)
      End Sub
    
      ''' <summary>
      ''' Handler to display the current picture
      ''' </summary>
      ''' <param name="sender">BindingSource</param>
      ''' <param name="e"></param>
      Private Sub LoadPicture(sender As Object, e As EventArgs)
        Dim bs = TryCast(sender, BindingSource)
        If bs Is Nothing OrElse bs.Current Is Nothing Then Exit Sub
        Dim ms As New MemoryStream
        Dim buf = CType(CType(bs.Current, DataRowView)("Picture"), Byte())
        ms.Write(buf, 0, buf.Length)
        pict.SuspendLayout()
        pict.Image = New Bitmap(ms)
        pict.ResumeLayout()
      End Sub
    
    End Class


    --
    Best Regards / Viele Grüße
    Peter Fleischer (former MVP for Developer Technologies)
    Homepage, Tipps, Tricks



    Friday, October 4, 2019 6:55 AM
  • Hi,

    Would you want this effect?

    If so, you can try my code as follows.

    I use Sql Sever instead. It's simply change it to Access.

    Imports System.Data.SqlClient
    Imports System.IO
    
    Public Class Form1
        Dim constr As String = "Data Source = (localdb)\MSSQLLocalDB; Integrated Security = True ;AttachDbFileName= D:\Local Database\190925.mdf"
        Dim cmd As SqlCommand
        Dim conn As SqlConnection
        Dim sda As SqlDataAdapter
        Dim dt As New DataTable
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            GetData()
        End Sub
    
        Sub GetData()
            Using conn = New SqlConnection(constr)
                conn.Open()
                sda = New SqlDataAdapter("Select * From student", conn)
                dt.Clear()
                sda.Fill(dt)
                DataGridView1.DataSource = dt
            End Using
        End Sub
    
        Private Sub DataGridView1_DoubleClick(sender As Object, e As EventArgs) Handles DataGridView1.DoubleClick
            Form2.TextBox1.Text = DataGridView1.CurrentRow.Cells(0).Value.ToString.Trim
            Form2.TextBox2.Text = DataGridView1.CurrentRow.Cells(1).Value.ToString.Trim
    
            Dim buf As MemoryStream = New MemoryStream(CType(DataGridView1.CurrentRow.Cells(4).Value, Byte()))
            Dim image As Image = Image.FromStream(buf, True)
            Form2.PictureBox1.Image = image
            Form2.Show()
        End Sub
    End Class

    Hope It be helpful.

    Best Regards,

    Julie


    MSDN Community Support Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, October 7, 2019 9:09 AM
    Moderator
  • Thanks for the reply I like the idea you introduced however I did already the codes which will load the data from the table of Database if the selected row is double clicked. This is the code on the form2 right after the selected row is double clicked from form1.

    To give you more understanding to what I did is I placed a datagrid view on form1 then manually added columns and kept the ID visible to false and Capture Image visible to false

    1.  Header Text = ID 
         DataPropertyName = AttID   'This is Column in Access database or index primary key auto                                                            number

    2. Header Text = First name
          DataPropertyName = fname  'This is column in Access database as TEXT

    3. Header Text = Last name
           DataPropertyName = lname  'This is column in Access database as TEXT

    4. Header Text = Time Stamp
           DataPropertyName = srno   ' This is column in Access database as TEXT

    5. Header Text = Data and Time
           DataPropertyName = datetime    'This is column in Access database as TEXT

    6. Header Text = Capture Picture
           DataPropertyName = capturedpic   'This is column in Access database as OLE Object

       Private Sub Load_Data()
            Command = New OleDbCommand
            Connection = New OleDbConnection(StrCon)

            With Connection
                If .State = ConnectionState.Closed Then
                    .ConnectionString = StrCon
                    .Open()
                End If
            End With

            With Command
                .Connection = Connection
                .CommandType = CommandType.Text
                .CommandText = " SELECT AttID, fname, lname, srno, datetime, capturedpic " &
                               " FROM Attendance WHERE AttID = " & txtFirstname.Tag
            End With

            Reader = Command.ExecuteReader
            If Reader.HasRows Then
                While Reader.Read
                    txtFirstname.Text = Reader("AttID")
                    txtFirstname.Text = IIf(Not IsDBNull(Reader("fname")), Reader("fname"), "")
                    txtLastname.Text = IIf(Not IsDBNull(Reader("lname")), Reader("lname"), "")
                    txtTimeStamp.Text = IIf(Not IsDBNull(Reader("srno")), Reader("srno"), "")
                    txtDateTime.Text = IIf(Not IsDBNull(Reader("datetime")), Reader("datetime"), "")

    ' supposedly on this line will lie the line of codes for the picture 

                End While
            End If
            Reader.Close()
            Connection.Close()
        End Sub

    Sunday, October 13, 2019 10:15 AM
  • Thanks for the reply I like the idea you introduced however I did already the codes which will load the data from the table of Database if the selected row is double clicked. This is the code on the form2 right after the selected row is double clicked from form1.

    To give you more understanding to what I did is I placed a datagrid view on form1 then manually added columns and kept the ID visible to false and Capture Image visible to false

    1.  Header Text = ID 
         DataPropertyName = AttID   'This is Column in Access database or index primary key auto                                                            number

    2. Header Text = First name
          DataPropertyName = fname  'This is column in Access database as TEXT

    3. Header Text = Last name
           DataPropertyName = lname  'This is column in Access database as TEXT

    4. Header Text = Time Stamp
           DataPropertyName = srno   ' This is column in Access database as TEXT

    5. Header Text = Data and Time
           DataPropertyName = datetime    'This is column in Access database as TEXT

    6. Header Text = Capture Picture
           DataPropertyName = capturedpic   'This is column in Access database as OLE Object

       Private Sub Load_Data()
            Command = New OleDbCommand
            Connection = New OleDbConnection(StrCon)

            With Connection
                If .State = ConnectionState.Closed Then
                    .ConnectionString = StrCon
                    .Open()
                End If
            End With

            With Command
                .Connection = Connection
                .CommandType = CommandType.Text
                .CommandText = " SELECT AttID, fname, lname, srno, datetime, capturedpic " &
                               " FROM Attendance WHERE AttID = " & txtFirstname.Tag
            End With

            Reader = Command.ExecuteReader
            If Reader.HasRows Then
                While Reader.Read
                    txtFirstname.Text = Reader("AttID")
                    txtFirstname.Text = IIf(Not IsDBNull(Reader("fname")), Reader("fname"), "")
                    txtLastname.Text = IIf(Not IsDBNull(Reader("lname")), Reader("lname"), "")
                    txtTimeStamp.Text = IIf(Not IsDBNull(Reader("srno")), Reader("srno"), "")
                    txtDateTime.Text = IIf(Not IsDBNull(Reader("datetime")), Reader("datetime"), "")

    ' supposedly on this line will lie the line of codes for the picture 

                End While
            End If
            Reader.Close()
            Connection.Close()
        End Sub
    Sunday, October 13, 2019 10:21 AM
  • Finally got it I added this chunk of code

     Dim bytImage() As Byte
                    bytImage = CType(Reader(5), Byte())
                    Dim ms As New MemoryStream(bytImage)
                    Dim bmImage As New Bitmap(ms)
                        ms.Close()
                    PictureBox1.Image = bmImage
                    PictureBox1.Refresh()

    • Marked as answer by jepoyman Sunday, October 13, 2019 12:05 PM
    Sunday, October 13, 2019 12:05 PM