none
A generic error occurred in GDI+ ..Error. RRS feed

  • Question

  • I want To Insert Image into Access Database,
    But I am getting " A generic error occurred in GDI+ ".
    First I'm  Displaying Image From database To DataGridView, then From DataGridView To PictureBox.
    I want To Insert This Image from PictureBox To DataBase.
    This the code I an Using For This:
    Code to display image from Dgv1 to PictureBox:

    Private Sub Dgv1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles Dgv1.CellContentClick
       Dim f1 as New Form3    
     Try
    
                Dim dr As Integer = Dgv1.CurrentCell.RowIndex + 0
                If dr > -1 Then                      
                        f1.CboRaces.Text = CStr(Dgv1.Rows(dr).Cells(2).Value)
                        f1.txtCage.Text = CInt(Dgv1.Rows(dr).Cells(3).Value)
                        If IsDBNull(Dgv1.Rows(dr).Cells("Photo").Value) = True Then
                        f1.Picture.Image = My.Resources.GiGi
                        Else
                            Dim data As Byte() = Dgv1.Rows(dr).Cells("Photo").Value
                            Using ms As New MemoryStream(data)
                                f1.Picture.Image = Image.FromStream(ms)
                            End Using
                        End If
               End If
    
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub

    cast

    Code To Insert Image To DataBase:

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
            Try
                Using cn As New OleDb.OleDbConnection With
                                 {
                                     .ConnectionString = Builder.ConnectionString
                                 }
                    Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
                        cn.Open()
                        cmd.CommandText = "INSERT INTO Pictures(CoupleID,Photo) VALUES(@d1,@d2)"
                        cmd.Parameters.AddWithValue("@d1", txtCode.Text)
                        Dim ms As New MemoryStream()
                        Picture.Image.Save(ms, Picture.Image.RawFormat)
                        Dim data As Byte() = ms.GetBuffer()
                        Dim p As New OleDbParameter("@d2", OleDbType.Binary)
                        p.Value = data
                        cmd.Parameters.Add(p)
                        cmd.ExecuteNonQuery()
                        MessageBox.Show(" Image has been saved", "Save", MessageBoxButtons.OK)
                        cmd.Parameters.Clear()
                    End Using
                End Using
    
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub



    Code To Display Image From Database To DataGridview:

    Module LoadPontes Public Function LoadDatas() As DataTable Dim dt As New DataTable Using cn As New OleDb.OleDbConnection With { .ConnectionString = Builder.ConnectionString } Using cmd As New OleDb.OleDbCommand With {.Connection = cn} cn.Open() Dim selectStatement As String = <SQL> SELECT TestingTable1.CoupleID , TestingTable1.Pontes , TestingTable1.Race ,TestingTable1.Cage ,Photo FROM TestingTable1 ,Pictures where Pontes like 'Ponte1' and TestingTable1.CoupleID= Pictures.CoupleID Order By Pontes </SQL>.Value cmd.CommandText = selectStatement dt.Load(cmd.ExecuteReader()) Return dt End Using End Using End Function End Module 'Load Datas into Dgv1

    Private Sub btnPonte2_Click(sender As Object, e As EventArgs) Handles btnPonte2.Click Dgv1.DataSource = LoadDatas() End Sub

    This Is all What I am Using.
    So thank you Very Much For your help.

    Best Regards.



    • Edited by Bajtitou Saturday, April 13, 2019 8:10 AM
    Saturday, April 13, 2019 7:47 AM

Answers

  • So the result must be 1, otherwise the image is not saved. If the result is 1 then after doing the insert close the application and open the database w/o your program, is the image there or not. 

    At this point I have given you code that works, does not make sense it's not working so nothing else to offer.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Bajtitou Saturday, April 13, 2019 11:28 PM
    Saturday, April 13, 2019 11:06 PM
    Moderator

All replies

  • Hi,
    which type has your field "Photo" in the access database?

    Please try type "image" for field "Photo" and use for parameter "OleDbType.LongVarBinary" for writing and for image format "Drawing.Imaging.ImageFormat.Jpeg".


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



    Saturday, April 13, 2019 9:10 AM
  • Hi,
    which type has your field "Photo" in the access database?

    Please try type "image" for field "Photo" and use for parameter "OleDbType.LongVarBinary" for writing and for image format "Drawing.Imaging.ImageFormat.Jpeg".


    Hi,

    Thank you very Much  for your assistance.

    The type Of Field "Photo"  is  "Objet OLE"

    Pictures are stocked as "binary data" in Pictures Table.

    cast

    So thank you .Best Regards.


    • Edited by Bajtitou Saturday, April 13, 2019 9:36 AM
    Saturday, April 13, 2019 9:29 AM
  • Try replacing ‘Using ms As New MemoryStream(data)’ with ‘Dim ms As New MemoryStream(data)’ (i.e. do not dispose this variable). Also replace ‘ms.GetBuffer’ with ‘ms.ToArray’.

    Saturday, April 13, 2019 9:48 AM
  • Hello,

    I have a complete code sample for you, give me a little time to update it from an older version of Visual Studio and will upload it to Microsoft OneDrive.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, April 13, 2019 9:59 AM
    Moderator
  • Hi,
    look for the demo:

    Option Strict On
    
    Imports System.Data.OleDb
    
    Public Class Form1
    
      Dim myPictureBox As New PictureBox
      Dim myDataGrid As New DataGrid
      Dim myCurrencyManager As CurrencyManager
    
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Context menu
        Dim cm As New ContextMenuStrip
        Dim ts As ToolStripMenuItem
        ' ToolStrips
        ts = New ToolStripMenuItem
        cm.Items.Add(ts)
        With ts
          .Text = "New Table"
          AddHandler .Click, AddressOf NewTable
        End With
        ts = New ToolStripMenuItem
        cm.Items.Add(ts)
        With ts
          .Text = "Load picture from file"
          AddHandler .Click, AddressOf LoadPict
        End With
        ts = New ToolStripMenuItem
        cm.Items.Add(ts)
        With ts
          .Text = "Insert picture into database"
          AddHandler .Click, AddressOf InsertPict
        End With
        ' PictureBox
        Me.Controls.Add(myPictureBox)
        With myPictureBox
          .Dock = DockStyle.Fill
          .SizeMode = PictureBoxSizeMode.StretchImage
          .ContextMenuStrip = cm
        End With
        ' list if ID's
        Me.Controls.Add(myDataGrid)
        With myDataGrid
          .Dock = DockStyle.Left
          .DataSource = PictureData.GetIDList
          AddHandler .Click, AddressOf GetPict
        End With
        '
        myCurrencyManager = CType(Me.BindingContext(PictureData.GetIDList, ""), CurrencyManager)
        AddHandler myCurrencyManager.PositionChanged, AddressOf GetPict
        GetPict(Me, Nothing)
      End Sub
    
      Private Sub NewTable(ByVal sender As Object, ByVal e As EventArgs)
        PictureData.CreateTable()
      End Sub
    
      Private Sub LoadPict(ByVal sender As Object, ByVal e As EventArgs)
        Dim ofd As New OpenFileDialog
        Try
          With ofd
            .ShowDialog()
            If .FileName <> "" Then
              myPictureBox.Image = Image.FromFile(.FileName)
            End If
          End With
        Catch ex As Exception
          MsgBox(ex.Message)
        End Try
      End Sub
    
      Private Sub InsertPict(ByVal sender As Object, ByVal e As EventArgs)
        PictureData.InsertPict(myPictureBox.Image)
        myDataGrid.DataSource = PictureData.GetIDList()
      End Sub
    
      Private Sub GetPict(ByVal sender As Object, ByVal e As EventArgs)
        If Not myCurrencyManager.Current Is Nothing Then
          Dim drv As DataRowView = CType(myCurrencyManager.Current, DataRowView)
          If Not drv Is Nothing Then
            If Not drv("ID") Is DBNull.Value Then
              myPictureBox.Image = PictureData.GetPict(CType(drv("ID"), Integer))
            End If
          End If
        End If
      End Sub
    
    End Class
    
    Public Class PictureData
      ' Connection
      Private Shared conString As String = My.Settings.cnMdb
      ' eg.: "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Me\VB6\test2K.mdb"
      Private Shared myOleDbConnection As OleDbConnection
      '
      Private Shared dt As New DataTable
    
      Shared Sub New()
        ' Connection object
        myOleDbConnection = New OleDbConnection(conString)
      End Sub
    
      Public Shared Function GetIDList() As DataView
        dt.Clear()
        Call (New OleDbDataAdapter("SELECT ID FROM XPict", myOleDbConnection)).Fill(dt)
        With dt
          With .DefaultView
            .AllowDelete = False
            .AllowEdit = False
            .AllowNew = False
          End With
          Return dt.DefaultView
        End With
    
      End Function
    
      Public Shared Sub CreateTable()
        Try
          myOleDbConnection.Open()
          Try
            Call (New OleDbCommand("DROP TABLE xPict", myOleDbConnection)).ExecuteNonQuery()
          Catch ex As Exception
          End Try
          Call (New OleDbCommand("CREATE TABLE xPict(ID autoincrement PRIMARY KEY, PictOle image)", myOleDbConnection)).ExecuteNonQuery()
        Catch ex As Exception
          MsgBox(ex.Message)
        Finally
          myOleDbConnection.Close()
        End Try
      End Sub
    
      ' paste picture from PictureBox into Ole field
      Public Shared Sub InsertPict(ByVal img As Image)
        Try
          Dim myMemoryStream As New System.IO.MemoryStream
          If img Is Nothing Then
            MsgBox("No Picture")
            Exit Sub
          End If
          img.Save(myMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg)
          Dim arrImage() As Byte = myMemoryStream.GetBuffer
          Dim strSQL As String = "INSERT INTO xPict (PictOle) VALUES (@Picture)"
          Dim myCommand As New OleDbCommand(strSQL, myOleDbConnection)
          myCommand.Parameters.Add(New OleDbParameter("@Picture", OleDbType.LongVarBinary)).Value = arrImage
          myOleDbConnection.Open()
          myCommand.ExecuteNonQuery()
        Catch ex As Exception
          MsgBox(ex.Message)
        Finally
          myOleDbConnection.Close()
        End Try
      End Sub
    
      Public Shared Function GetPict(ByVal id As Integer) As Image
        Try
          Dim strSQL As String = "SELECT PictOle FROM xPict WHERE ID = @ID"
          Dim myCommand As New OleDbCommand(strSQL, myOleDbConnection)
          myCommand.Parameters.Add(New OleDbParameter("@ID", OleDbType.Integer)).Value = id
          myOleDbConnection.Open()
          Dim myReader As OleDbDataReader
          myReader = myCommand.ExecuteReader
          If myReader.Read() Then
            Dim myArrayBuffer(999999) As Byte
            myReader.GetBytes(0, 0, myArrayBuffer, 0, 1000000)
            Dim myMemoryStream As New System.IO.MemoryStream(myArrayBuffer)
            Return New Bitmap(myMemoryStream)
          Else
            Return Nothing
          End If
        Catch ex As Exception
          MsgBox(ex.Message)
          Return Nothing
        Finally
          myOleDbConnection.Close()
        End Try
      End Function
    
    End Class
    


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

    Saturday, April 13, 2019 10:08 AM
  • Hello,

    I have a complete code sample for you, give me a little time to update it from an older version of Visual Studio and will upload it to Microsoft OneDrive.


    Hi, 

    Thank you very much, take your time, I am waiting patiently.

    Best Regards.

    Saturday, April 13, 2019 10:55 AM
  • Hello,

    First off I don't simply insert an image but also store a category, original file name and a description so that later in the program we can categorize images and export them to their original name.

    Secondly, there is a great deal of other code that you may find useful in the source code :-)

    In the following example the PictureBox is on a secondary form (but) the same works if the PictureBox was on the same form as the DataGridView.

    Data is loaded from a database at program startup. Select an image in the DataGridView, select PictureBox button on right, the picture box form shows the current image selected in the DataGridView (so it's like the image shown in the picture box was on the main form).

    Pressing "Insert image" button gets data for the PictureBox

    Private Sub insertImageButton_Click(sender As Object, e As EventArgs) Handles insertImageButton.Click
        Dim Row = CType(bsData.Current, DataRowView).Row
    
        Dim ops = New Operations
        ops.AddImage1(
            Row.Field(Of Byte())("Picture"),
            Row.Field(Of Integer)("Category"),
            Row.Field(Of String)("Description"),
            Row.Field(Of String)("BaseName"),
            Row.Field(Of String)("FileExtension"))
    
    End Sub

    Then the definition for the call above to insert the image

    Public Function AddImage1(
    	imageByteArray As Byte(),
    	category As Integer,
    	description As String,
    	baseFileName As String,
    	fileExtension As String) As Boolean
    
    	Using cn As New OleDbConnection With {.ConnectionString = CodeModules.Builder.ConnectionString}
    		Using cmd As New OleDbCommand With {.Connection = cn}
    			cmd.CommandText =
    				<SQL>
    				INSERT INTO Pictures 
    				(
    					Category,
    					Picture,
    					Description,
    					BaseName,
    					FileExtension
    				) 
    				Values
    				(
    					@Category,
    					@Picture,
    					@Description,
    					@BaseName,
    					@FileExtension
    				)
    			</SQL>.Value
    
    
    			cmd.Parameters.AddRange(
    				New OleDbParameter() _
    				{
    					New OleDbParameter With
    					{
    						.ParameterName = "@Category",
    						.DbType = DbType.Int32,
    						.Value = category
    					},
    					New OleDbParameter With
    					{
    						.ParameterName = "@Picture",
    						.OleDbType = OleDbType.Binary,
    						.Value = imageByteArray
    					},
    					New OleDbParameter With
    					{
    						.ParameterName = "@Description",
    						.DbType = DbType.String,
    						.Value = description
    					},
    					New OleDbParameter With
    					{
    						.ParameterName = "@BaseName",
    						.DbType = DbType.String,
    						.Value = baseFileName},
    					New OleDbParameter With
    					{
    						.ParameterName = "@FileExtension",
    						.DbType = DbType.String,
    						.Value = fileExtension
    					}
    				}
    			)
    
    			Try
    				cn.Open()
    				Dim affected As Integer = cmd.ExecuteNonQuery
    				If affected = 1 Then
    					Return True
    				Else
    					Return False
    				End If
    			Catch ex As Exception
    				Return False
    			End Try
    		End Using
    	End Using
    End Function
    

    Full source code.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, April 13, 2019 11:01 AM
    Moderator
  • Hi Bajtitou,
    here is a demo for Visual Studio 2017 or 2019. Put the code in an empty Form. Click the ContextMenu in PictureBox (right click) to create database table, load image or save loaded image in database. Navigating in DataGrid at left side will show the Image from database. In Settings you can set the connection string ("cnMdb").

    Imports System.Data.OleDb
    
    Public Class Form2019
    
      Private cm As New ContextMenuStrip
      Private myPictureBox As New PictureBox With {.Dock = DockStyle.Fill,
          .SizeMode = PictureBoxSizeMode.StretchImage,
          .ContextMenuStrip = cm}
      Private myDataGrid As New DataGrid With {.Dock = DockStyle.Left}
      Private myCurrencyManager As CurrencyManager
    
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ' Context menu
        Dim ts As ToolStripMenuItem
        ' ToolStrips
        ts = New ToolStripMenuItem With {.Text = "New Table"}
        cm.Items.Add(ts)
        AddHandler ts.Click, AddressOf NewTable
        ts = New ToolStripMenuItem With {.Text = "Load picture from file"}
        cm.Items.Add(ts)
        AddHandler ts.Click, AddressOf LoadPict
        ts = New ToolStripMenuItem With {.Text = "Insert picture into database"}
        cm.Items.Add(ts)
        AddHandler ts.Click, AddressOf InsertPict
        ' PictureBox
        Me.Controls.Add(myPictureBox)
        ' list if ID's
        Me.Controls.Add(myDataGrid)
        With myDataGrid
          myDataGrid.DataSource = PictureData2019.GetIDList
          AddHandler myDataGrid.Click, AddressOf GetPict
        End With
        '
        myCurrencyManager = CType(Me.BindingContext(myDataGrid.DataSource, ""), CurrencyManager)
        AddHandler myCurrencyManager.PositionChanged, AddressOf GetPict
        GetPict(Me, Nothing)
      End Sub
    
      Private Sub NewTable(ByVal sender As Object, ByVal e As EventArgs)
        PictureData2019.CreateTable()
      End Sub
    
      Private Sub LoadPict(ByVal sender As Object, ByVal e As EventArgs)
        Dim ofd As New OpenFileDialog
        Try
          With ofd
            .ShowDialog()
            If .FileName <> "" Then myPictureBox.Image = Image.FromFile(.FileName)
          End With
        Catch ex As Exception
          MsgBox(ex.Message)
        End Try
      End Sub
    
      Private Sub InsertPict(ByVal sender As Object, ByVal e As EventArgs)
        PictureData2019.InsertPict(myPictureBox.Image)
        myDataGrid.DataSource = PictureData2019.GetIDList()
      End Sub
    
      Private Sub GetPict(ByVal sender As Object, ByVal e As EventArgs)
        If myCurrencyManager.Position >= 0 AndAlso myCurrencyManager.Current IsNot Nothing Then
          Dim drv As DataRowView = CType(myCurrencyManager.Current, DataRowView)
          If drv IsNot Nothing AndAlso drv("ID") IsNot DBNull.Value Then
            myPictureBox.Image = PictureData2019.GetPict(CType(drv("ID"), Integer))
          End If
        End If
      End Sub
    End Class
    
    Public Class PictureData2019
      ' Connection
      Private Shared conString As String = My.Settings.cnMdb
      ' eg.: "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\temp\DB.mdb"
      Private Shared myOleDbConnection As OleDbConnection
      '
      Private Shared dt As New DataTable
    
      Shared Sub New()
        ' Connection object
        myOleDbConnection = New OleDbConnection(conString)
      End Sub
    
      Public Shared Function GetIDList() As DataView
        dt.Clear()
        Try
          Call (New OleDbDataAdapter("SELECT ID FROM DemoImg", myOleDbConnection)).Fill(dt)
        Catch ex As Exception
          MsgBox(ex.Message)
        End Try
        With dt
          With .DefaultView
            .AllowDelete = False
            .AllowEdit = False
            .AllowNew = False
          End With
          Return dt.DefaultView
        End With
    
      End Function
    
      Public Shared Sub CreateTable()
        Try
          If myOleDbConnection.State = ConnectionState.Closed Then myOleDbConnection.Open()
          Try
            Using cmd As New OleDbCommand("DROP TABLE DemoImg", myOleDbConnection)
              cmd.ExecuteNonQuery()
            End Using
          Catch ex As Exception
          End Try
          Using cmd As New OleDbCommand("CREATE TABLE DemoImg(ID autoincrement PRIMARY KEY, Img image)", myOleDbConnection)
            cmd.ExecuteNonQuery()
          End Using
        Catch ex As Exception
          MsgBox(ex.Message)
        Finally
          myOleDbConnection.Close()
        End Try
      End Sub
    
      ' paste picture from PictureBox into Ole field
      Public Shared Sub InsertPict(ByVal img As Image)
        Try
          Using ms As New System.IO.MemoryStream
            If img Is Nothing Then
              MsgBox("No Picture")
              Exit Sub
            End If
            img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
            Dim strSQL As String = "INSERT INTO DemoImg(Img) VALUES (@Picture)"
            If myOleDbConnection.State = ConnectionState.Closed Then myOleDbConnection.Open()
            Using cmd As New OleDbCommand(strSQL, myOleDbConnection)
              cmd.Parameters.Add(New OleDbParameter("@Picture", OleDbType.LongVarBinary)).Value = ms.GetBuffer
              cmd.ExecuteNonQuery()
            End Using
          End Using
        Catch ex As Exception
          MsgBox(ex.Message)
        Finally
          myOleDbConnection.Close()
        End Try
      End Sub
    
      Public Shared Function GetPict(ByVal id As Integer) As Image
        Try
          Dim strSQL As String = "SELECT Img FROM DemoImg WHERE ID = @ID"
          If myOleDbConnection.State = ConnectionState.Closed Then myOleDbConnection.Open()
          Using cmd As New OleDbCommand(strSQL, myOleDbConnection)
            cmd.Parameters.Add(New OleDbParameter("@ID", OleDbType.Integer)).Value = id
            Using rdr As OleDbDataReader = cmd.ExecuteReader
              If rdr.Read() Then
                Dim myArrayBuffer(9999999) As Byte
                rdr.GetBytes(0, 0, myArrayBuffer, 0, 10000000)
                Using ms As New System.IO.MemoryStream(myArrayBuffer)
                  Return New Bitmap(ms)
                End Using
              Else
                Return Nothing
              End If
            End Using
          End Using
        Catch ex As Exception
          MsgBox(ex.Message)
          Return Nothing
        Finally
          myOleDbConnection.Close()
        End Try
      End Function
    
    End Class


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

    Saturday, April 13, 2019 4:38 PM
  • Try replacing ‘Using ms As New MemoryStream(data)’ with ‘Dim ms As New MemoryStream(data)’ (i.e. do not dispose this variable). Also replace ‘ms.GetBuffer’ with ‘ms.ToArray’.

    Hi,

    Forgive me I did not see this Post ..
    I had already tried it but without result.

    So Thank you very Much .

    Best Regards.

    Saturday, April 13, 2019 5:13 PM
  • Hi,
    look for the demo:

      ' paste picture from PictureBox into Ole field
      Public Shared Sub InsertPict(ByVal img As Image)
        Try
          Dim myMemoryStream As New System.IO.MemoryStream
          If img Is Nothing Then
            MsgBox("No Picture")
            Exit Sub
          End If
          img.Save(myMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg)
          Dim arrImage() As Byte = myMemoryStream.GetBuffer
          Dim strSQL As String = "INSERT INTO xPict (PictOle) VALUES (@Picture)"
          Dim myCommand As New OleDbCommand(strSQL, myOleDbConnection)
          myCommand.Parameters.Add(New OleDbParameter("@Picture", OleDbType.LongVarBinary)).Value = arrImage
          myOleDbConnection.Open()
          myCommand.ExecuteNonQuery()
        Catch ex As Exception
          MsgBox(ex.Message)
        Finally
          myOleDbConnection.Close()
        End Try
      End Sub
    
     

    Hi, 

    I am working On the Demo.

    But the Insert  code seems to me like the one I use above .

    Thank you very Much and Best Regards.


    Saturday, April 13, 2019 5:24 PM

  • Private Sub insertImageButton_Click(sender As Object, e As EventArgs) Handles insertImageButton.Click
        Dim Row = CType(bsData.Current, DataRowView).Row
    
        Dim ops = New Operations
        ops.AddImage1(
            Row.Field(Of Byte())("Picture"),
            Row.Field(Of Integer)("Category"),
            Row.Field(Of String)("Description"),
            Row.Field(Of String)("BaseName"),
            Row.Field(Of String)("FileExtension"))
    
    End Sub


    Hi, 

    I tried your example but I get an Exception: "The object reference is not defined to an instance of an object."

    cast

    So What is wrong!

    thank you very Much .

    Best Regards.

    Saturday, April 13, 2019 5:29 PM
  • You received this exception because on the line above you created a new BindingSource and have not set the DataSource so this means bsData.Current is null/Nothing.

    The proper way is to create the BindingSource at form level e.g.

    Public Class frmMainForm
        WithEvents _bsData As New BindingSource

    Using code from the main form in the project I presented in form load you do the following, replace ops.PictureDataTable with you instance of a populated DataTable.

    _bsData.DataSource = ops.PictureDataTable

    Then when you need to accecss .Current property of the BindingSource you can check for null/nothing first.

    If _bsData.Current IsNot Nothing Then

    If IsNot Nothing is true you can then safely access the DataRow

    CType(_bsData.Current, DataRowView).Row
    Does this make sense?


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, April 13, 2019 6:02 PM
    Moderator

  • If _bsData.Current IsNot Nothing Then

    If IsNot Nothing is true you can then safely access the DataRow

    CType(_bsData.Current, DataRowView).Row
    Does this make sense?

    Hi,

    Well, it's very clear now, But
    There is no photo add in database.

    Thank you Very Much

    Saturday, April 13, 2019 6:38 PM
  • Did you run my code sample and if so it worked right? So we need to figure out why your code is not adding a picture. Can you show the current code in your project?

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, April 13, 2019 6:42 PM
    Moderator
  • Did you run my code sample and if so it worked right? So we need to figure out why your code is not adding a picture. Can you show the current code in your project?


    Hi,

    I am using Your Samples : "Reading and writing images to MS-Access 2007 and higher databases"

    Sampes

    _ I create a new Table  Pictures2 In Database.

    _ I have add to Operations Class This Code:

     Public Function AddImage1(
        category As Integer,
        imageByteArray As Byte(),
        description As String,
        baseFileName As String,
        fileExtension As String) As Boolean
    
            Dim conn As MS_AccessConnection = MS_AccessConnection.GetInstance()
            cn = conn.GetConnection(Builder.ConnectionString)
            Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
                cmd.CommandText =
                <SQL>
    				INSERT INTO Pictures2 
    				(
    					Category,
    					Picture,
    					Description,
    					BaseName,
    					FileExtension
    				) 
    				Values
    				(
    					@Category,
    					@Picture,
    					@Description,
    					@BaseName,
    					@FileExtension
    				)
    			</SQL>.Value
    
    
                cmd.Parameters.AddRange(
                New OleDbParameter() _
                {
                    New OleDbParameter With
                    {
                        .ParameterName = "@Category",
                        .DbType = DbType.Int32,
                        .Value = category
                    },
                    New OleDbParameter With
                    {
                        .ParameterName = "@Picture",
                        .OleDbType = OleDbType.Binary,
                        .Value = imageByteArray
                    },
                    New OleDbParameter With
                    {
                        .ParameterName = "@Description",
                        .DbType = DbType.String,
                        .Value = description
                    },
                    New OleDbParameter With
                    {
                        .ParameterName = "@BaseName",
                        .DbType = DbType.String,
                        .Value = baseFileName},
                    New OleDbParameter With
                    {
                        .ParameterName = "@FileExtension",
                        .DbType = DbType.String,
                        .Value = fileExtension
                    }
                }
            )
    
                Try
                    cn.Open()
                    Dim affected As Integer = cmd.ExecuteNonQuery
                    If affected = 1 Then
                        Return True
                    Else
                        Return False
                    End If
                Catch ex As Exception
                    Return False
                End Try
            End Using
        
        End Function

    _ The btnInsert Image To PictureBoxForm and this code :

     Private Sub btnInserImages_Click(sender As Object, e As EventArgs) Handles btnInserImages.Click
          
            If _bsData.Current IsNot Nothing Then
                Dim Row = CType(_bsData.Current, DataRowView).Row
                Dim ops = New Operations
                ops.AddImage1(
                Row.Field(Of Integer)("Category"),
                Row.Field(Of Byte())("Picture"),
                Row.Field(Of String)("Description"),
                Row.Field(Of String)("BaseName"),
                Row.Field(Of String)("FileExtension"))
                MessageBox.Show(" Image has been saved", "Save", MessageBoxButtons.OK)
            End If
        End Sub

    Thank you very Much For you assistance and  Your patience with me.

    Best Regards.






    • Edited by Bajtitou Saturday, April 13, 2019 9:51 PM
    Saturday, April 13, 2019 7:17 PM
  • Hello,

    Place a breakpoint on the line for affected, run the code, which line is doing the return as per the highlights.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, April 13, 2019 8:06 PM
    Moderator


  • Hi,

     i have Placed a breakpoint on the line for affected No result.

    The application  run well but no Image Inserted to database.

    Thank you Very Much.

    Saturday, April 13, 2019 9:38 PM
  • In your image I expected to see (or you to indicate the value) the value as per below.

    Here 1 indicates the insert succeeded. What did you get??? 


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, April 13, 2019 10:18 PM
    Moderator
  • In your image I expected to see (or you to indicate the value) the value as per below.

    Here 1 indicates the insert succeeded. What did you get??? 


    Hi, 

    The message indicates that the image is save but there is nothing in database.

    But when I tested With This code image is saving:

     Private Sub btnInsert_Click(sender As Object, e As EventArgs) Handles btnInsert.Click
            Try
                Dim conn As MS_AccessConnection = MS_AccessConnection.GetInstance()
                cn = conn.GetConnection(Builder.ConnectionString)
                Using cmd As New OleDb.OleDbCommand With {.Connection = cn}
    
                    cmd.CommandText = "INSERT INTO Pictures2(Picture) VALUES(@Image)"
            
                    Dim ms As New MemoryStream()
                    PictureBox1.Image.Save(ms, PictureBox1.Image.RawFormat)
                    Dim data As Byte() = ms.GetBuffer()
                    Dim p As New OleDbParameter("@Image", OleDbType.Binary)
                    p.Value = data
                    cmd.Parameters.Add(p)
                    cmd.ExecuteNonQuery()
                    MessageBox.Show(" Image has been saved", "Save", MessageBoxButtons.OK)
                    cmd.Parameters.Clear()
                End Using
            Catch ex As Exception
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try
        End Sub

    On the other hand it does not work in my aapplication..it's a real headache!

    thank you very Much.


    • Edited by Bajtitou Saturday, April 13, 2019 10:45 PM
    Saturday, April 13, 2019 10:43 PM
  • So the result must be 1, otherwise the image is not saved. If the result is 1 then after doing the insert close the application and open the database w/o your program, is the image there or not. 

    At this point I have given you code that works, does not make sense it's not working so nothing else to offer.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Marked as answer by Bajtitou Saturday, April 13, 2019 11:28 PM
    Saturday, April 13, 2019 11:06 PM
    Moderator
  • So the result must be 1, otherwise the image is not saved. If the result is 1 then after doing the insert close the application and open the database w/o your program, is the image there or not. 

    At this point I have given you code that works, does not make sense it's not working so nothing else to offer.

    I will review the code step by step and look where is the error.

    Thank you very much and best Regards.

    Saturday, April 13, 2019 11:28 PM