none
Help appreciated with a test program RRS feed

  • Question

  • I have some 11 vb.net programs (each containing 1000's of code lines) and with several access databases as backend, to convert from ADODB using Jet to ADO.Net.
    I have been using VB.2010 (and previous versions) for more than 15 years, but this ADO.Net is quite new (and time consuming) to me. I decided to make a small test project where I could try out the various functions required to make my programs work - and of course ran headlong into a bunch of problems.
    The program is performing ok in the "Form1_Load", "List1_SelectedIndexChanged", the "cmdDeleteCompany_Click" and the "ShowPicture()"

    1. problem:  can not make updates to a DataSet (Private Sub SaveData), get no errors through!
    2. problem:  can not insert a picture into the DataSet (cmdNewPic_Click), got the error "A first chance exception of type 'System.AccessViolationException' occurred in System.Windows.Forms.dll" at the line:  "If fileDialogBox.ShowDialog() = DialogResult.OK Then"
    3. problem:  can not insert a new record (row) in the DataSet, no error is given though!
    4. problem:  can not update the database with a changed DataSet (Form1_FormClosing), get no errors through!

    I would be very happy if someone would read through my code and point out where I have gone wrong. I can not start converting my programs before I am sure this test program is functioning perfect.

    Kind regards
    Jorgen

    Code as is:

    Option Explicit On
    Option Strict On
    Imports System.IO
    Imports System.Drawing
    Imports System.Data.OleDb
    Public Class Form1
        Dim strSql As String = ""
        Dim path As String = ""
        Dim lngCurrent As Long = 0
        Dim boolNewRecord As Boolean

        Public Const IDYES = 6                 ' Yes button pressed
        Public Const MB_YESNO = 4              ' Yes and No buttons
        Public Const MB_ICONQUESTION = 32      ' Warning query
        Public Const MB_DEFBUTTON2 = 256       ' Second button is default

        Public m_strSchedulesConnect As String
        Public dsCompany As New DataSet

        Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
            'if changes to the DateSet, then update database
            If dsCompany.HasChanges() Then
                strSql = "SELECT * FROM Company"
                Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                    conSchedules.Open()
                    Using oledbAdapter As New OleDbDataAdapter(strSql, conSchedules)
                        oledbAdapter.Update(dsCompany, "Company")
                    End Using
                End Using
            End If
        End Sub

        Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            Dim path = My.Application.Info.DirectoryPath
            m_strSchedulesConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & path & "\Schedules.db2;Jet OLEDB:Database Password=karianne2010;"
            Try
                Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                    conSchedules.Open()
                    Using oledbAdapter As New OleDbDataAdapter("SELECT * From Company ORDER BY CompName", conSchedules)
                        Dim ds As DataSet = New DataSet
                        oledbAdapter.Fill(ds, "Company")
                        For i As Integer = 0 To ds.Tables("Company").Rows.Count - 1
                            List1.Items.Add(ds.Tables("Company").Rows(i).Item("CompName").ToString)
                            List1_1.Items.Add(ds.Tables("Company").Rows(i).Item("Counter"))
                        Next
                    End Using
                End Using

            Catch ex As Exception
                Debug.Print(ex.StackTrace & " - Load")
            End Try
        End Sub

        Private Function SelectCompany(lngID As Long) As Boolean
            strSql = "SELECT * FROM Company WHERE CLng(Counter) ="
            strSql = strSql & Chr(34) & lngID & Chr(34)

            dsCompany = New DataSet
            Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                conSchedules.Open()
                Using oledbAdapter As New OleDbDataAdapter(strSql, conSchedules)
                    oledbAdapter.Fill(dsCompany, "Company")
                End Using
            End Using

            If dsCompany.Tables("Company").Rows.Count > 0 Then
                Debug.Print(dsCompany.Tables("Company").Rows(0).Item("CompName").ToString & " - from Select")
                Return True
            Else
                Return False
            End If
        End Function

        Private Sub ShowData()
            If dsCompany.Tables("Company").Rows.Count > 0 Then
                txtCompany.Text = dsCompany.Tables("Company").Rows(0).Item("CompName").ToString
                txtMail.Text = dsCompany.Tables("Company").Rows(0).Item("CompEMail").ToString
                txtWeb.Text = dsCompany.Tables("Company").Rows(0).Item("CompURL").ToString

                ShowPicture()
            Else
                txtCompany.Text = ""
                txtMail.Text = ""
                txtWeb.Text = ""
            End If

        End Sub

        Private Sub SaveData()
            If Not dsCompany.Tables("Company").Rows.Count > 0 Then Exit Sub

            Dim drCurrent As DataRow
            drCurrent = dsCompany.Tables("Company").Rows(0)
            drCurrent.BeginEdit()
            drCurrent("CompName") = txtCompany.Text
            drCurrent("CompEMail") = txtMail.Text
            drCurrent("CompURL") = txtWeb.Text
            drCurrent.EndEdit()
        End Sub

        Private Sub List1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles List1.SelectedIndexChanged
            'when List1 index changes, update old values if necessary, and read new values
            If Len(txtCompany.Text) <> 0 Then
                If SelectCompany(lngCurrent) Then
                    If dsCompany.HasChanges Then

                        SaveData()

                        txtCompany.Text = ""
                        txtMail.Text = ""
                        txtWeb.Text = ""
                    End If
                End If
            End If

            List1_1.SelectedIndex = List1.SelectedIndex

            lngCurrent = CLng(List1_1.SelectedItem)
            If SelectCompany(lngCurrent) Then
                ShowData()
            End If
        End Sub

        Private Sub cmdNewPic_Click(sender As System.Object, e As System.EventArgs) Handles cmdNewPic.Click
            'import a picture from disk into the DataSet
            Try
                Dim fileDialogBox As OpenFileDialog = New OpenFileDialog()

                If fileDialogBox.ShowDialog() = DialogResult.OK Then
                    PictureBox1.Image = Image.FromFile(fileDialogBox.FileName)

                    Dim my_stream As New FileStream(fileDialogBox.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)
                    Dim bytes_stream(CInt(my_stream.Length) - 1) As Byte
                    my_stream.Read(bytes_stream, 0, bytes_stream.Length)

                    Dim drCurrent As DataRow
                    drCurrent = dsCompany.Tables("Company").Rows(0)
                    drCurrent.BeginEdit()
                    drCurrent("CompLogo") = my_stream
                    drCurrent.EndEdit()

                End If
            Catch ex As Exception
                Debug.Write(ex.StackTrace)
            End Try
        End Sub

        Private Sub cmdDeletePic_Click(sender As System.Object, e As System.EventArgs) Handles cmdDeletePic.Click
            'delete the shown picture
            Dim DgDef As Long
            Dim Msg As String
            Dim Response As Integer
            Dim Title As String
            DgDef = MB_YESNO + MB_ICONQUESTION + MB_DEFBUTTON2

            On Error Resume Next
            Title = "DELETE RECORD"
            Msg = "Do you really want to delete this Company logo Picture ?"
            Response = MsgBox(Msg, CType(DgDef, MsgBoxStyle), Title)
            If Response = IDYES Then
                Dim drCurrent As DataRow
                drCurrent = dsCompany.Tables("Company").Rows(0)
                drCurrent.BeginEdit()
                drCurrent("CompLogo") = ""
                drCurrent.EndEdit()
                PictureBox1.Image = Nothing
            End If
        End Sub

        Private Sub ShowPicture()
            'show the table picture, if any
            Dim cn As New OleDbConnection
            Dim cmd As New OleDbCommand
            Dim dr As OleDbDataReader

            cn.ConnectionString = m_strSchedulesConnect
            cn.Open()
            cmd = cn.CreateCommand()
            cmd.CommandText = "SELECT * FROM Company WHERE CLng(Counter) = '" & CLng(List1_1.SelectedItem) & "'"
            dr = cmd.ExecuteReader

            If Not dr.HasRows Then
                PictureBox1.Image = Nothing
                Exit Sub
            End If

            Try
                If dr.Read Then
                    If dr("CompLogo").ToString = "" Then
                        PictureBox1.Image = Nothing
                        Exit Sub
                    End If

                    Dim bytImage() As Byte
                    bytImage = CType(dr("CompLogo"), Byte())
                    If bytImage Is Nothing Then Exit Sub
                    Dim ms As New System.IO.MemoryStream(bytImage)
                    Dim bytePic As New Bitmap(ms)
                    ms.Close()
                    PictureBox1.Image = bytePic
                    PictureBox1.Refresh()
                    Call StretchSourcePictureFromPicture(bytePic, PictureBox1)
                    bytePic = Nothing
                Else
                    PictureBox1.Image = Nothing
                End If

            Catch ex As Exception
                Debug.Print(ex.ToString)
            End Try

            dr.Close()
            cn.Close()

        End Sub

        Private Sub cmdPastePic_Click(sender As System.Object, e As System.EventArgs) Handles cmdPastePic.Click

            'If image exists in the clipboard, paste it into the picture box
            If My.Computer.Clipboard.ContainsImage Then
                PictureBox1.Image = My.Computer.Clipboard.GetImage
                PictureBox1.Image.Save(My.Application.Info.DirectoryPath & "\TempPicture.bmp")

                Dim cn As New OleDbConnection
                Dim cmd As New OleDbCommand
                Dim dr As OleDbDataReader

                cn.ConnectionString = m_strSchedulesConnect
                cn.Open()
                cmd = cn.CreateCommand()
                cmd.CommandText = "SELECT * FROM Company WHERE CLng(Counter) = '" & CLng(List1_1.SelectedItem) & "'"
                dr = cmd.ExecuteReader

                Dim fs As FileStream = New FileStream(My.Application.Info.DirectoryPath & "\TempPicture.bmp", FileMode.Open, FileAccess.Read, FileShare.Read)
                Dim sr As StreamReader = New StreamReader(fs)
                Dim FileByteArray(CInt(fs.Length) - 1) As Byte
                fs.Read(FileByteArray, 0, CInt(fs.Length))
                cmd.Parameters.Add("@CompLogo", System.Data.OleDb.OleDbType.Binary, CInt(fs.Length)).Value = FileByteArray
                cmd.ExecuteNonQuery()
                cn.Close()
            Else
                MsgBox("The Clipbord does not contain any valid image!")
            End If
        End Sub

        Private Sub cmdCopyPic_Click(sender As System.Object, e As System.EventArgs) Handles cmdCopyPic.Click
            'Copy the picture from the picture box onto the clipboard
            My.Computer.Clipboard.Clear()
            My.Computer.Clipboard.SetImage(PictureBox1.Image)
        End Sub

        Private Sub StretchSourcePictureFromPicture(ByVal picSrc As Bitmap, ByVal picDest As PictureBox)
            On Error Resume Next
            Dim bm_source As Bitmap

            bm_source = picSrc

            Dim bm_dest As New Bitmap(CInt(picDest.Width), CInt(picDest.Height))
            Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)

            gr_dest.DrawImage(bm_source, 0, 0, bm_dest.Width + 1, bm_dest.Height + 1)
            picDest.Image = bm_dest

        End Sub

        Private Sub cmdNewCompany_Click(sender As System.Object, e As System.EventArgs) Handles cmdNewCompany.Click
            txtCompany.Text = ""
            txtMail.Text = ""
            txtWeb.Text = ""

            boolNewRecord = True
            txtCompany.Focus()
        End Sub

        Private Sub txtCompany_LostFocus(sender As Object, e As System.EventArgs) Handles txtCompany.LostFocus
            If boolNewRecord = True Then
                If Len(txtCompany.Text) <> 0 Then Exit Sub
                Dim Row As DataRow = dsCompany.Tables("Company").NewRow()
                Row("CompName") = txtCompany.Text
                dsCompany.Tables("Company").Rows.Add(Row)

                List1.Items.Clear()
                List1_1.Items.Clear()
                'add the new row to the ListBox
                For i As Integer = 0 To dsCompany.Tables("Company").Rows.Count - 1
                    List1.Items.Add(dsCompany.Tables("Company").Rows(i).Item("CompName").ToString)
                    List1_1.Items.Add(dsCompany.Tables("Company").Rows(i).Item("Counter"))
                Next

                boolNewRecord = False
            End If
        End Sub

        Private Sub cmdDeleteCompany_Click(sender As System.Object, e As System.EventArgs) Handles cmdDeleteCompany.Click
            strSql = "DELETE * from Company WHERE CLng(Counter) = '" & CLng(List1_1.SelectedItem) & "'"
            Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                conSchedules.Open()
                Using dbCommand As OleDbCommand = New OleDb.OleDbCommand(strSql, conSchedules)
                    'delete the database table
                    dbCommand.ExecuteNonQuery()

                    'fill the ListBox once again
                    List1.Items.Clear()
                    List1_1.Items.Clear()
                    Dim ds As New DataSet
                    strSql = "SELECT * From Company ORDER BY CompName"
                    Using oledbAdapter As New OleDbDataAdapter(strSql, conSchedules)
                        oledbAdapter.Fill(ds, "Company")
                        For i As Integer = 0 To ds.Tables("Company").Rows.Count - 1
                            List1.Items.Add(ds.Tables("Company").Rows(i).Item("CompName").ToString)
                            List1_1.Items.Add(ds.Tables("Company").Rows(i).Item("Counter"))
                        Next
                    End Using
                End Using
            End Using
        End Sub
    End Class


    levesen





    • Edited by levesen Monday, October 15, 2012 8:30 PM
    Monday, October 15, 2012 3:45 PM

Answers

All replies

  • Hi Levesen,

    1) I suspect that the SaveData() isn't working because the only place you call it is in the SelectedIndexChanged() event handler and at that point your DataSet doesn't have any changes (and yet, you are checking to see if it does before calling SaveData(). Have you traced this at all in the debugger? I suspect not, because this should have been fairly obvious if you had. In your SelectedIndexChanged() event handler, you call the SelectCompany() method, which creates and fills your DataSet. At this point, the DataSet.HasChanges will be false.

    2) Sounds like a problem with accessing whatever file you're trying to access with the fileDialogBox. Can't help you there.

    3) The only place I see where you're adding a new record is in the txtCompany_LostFocus. But then, you are wiping it all out when you call the SelectCompany() method, so perhaps that's part of the problem too.

    4) Similar to #1, your DataSet.HasChanges is still probably false.


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Tuesday, October 16, 2012 2:54 PM
  • Hi again,
    I have now re-worked the whole test program, and 'just' got 2 subs which is not working:
    "cmdNewPic_Click"  and  "cmdPastePic_Click"
    I have put the question about solving those problems in the 'ADO.NET DataSet forum', but if you would be so kind to help me out I would be vert grateful.

    Kind regards
    Jorgen

    Here is the new updated code:

    Option Explicit On
    Option Strict On
    Imports System.IO
    Imports System.Drawing
    Imports System.Data.OleDb

    Public Class Form1
        Dim strSql As String = ""
        Dim path As String = ""
        Dim lngCurrent As Long = 0
        Dim boolNewRecord As Boolean = False

        Public m_strSchedulesConnect As String
        Public m_Path As String
        Public dsCompany As New DataSet

        Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
            '*************** ok
            'if changes to the DateSet, then update database
            SaveData
        End Sub

        Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            '*************** ok
            Dim m_path = My.Application.Info.DirectoryPath
            m_strSchedulesConnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & m_path & "\Schedules.db2;Jet OLEDB:Database Password=karianne2010;"
            LoadData()
        End Sub

        Private Sub LoadData()
            Try
                Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                    conSchedules.Open()
                    strSql = "SELECT * From Company ORDER BY CompName"
                    Using oledbAdapter As New OleDbDataAdapter(strSql, conSchedules)
                        Dim ds As DataSet = New DataSet
                        oledbAdapter.Fill(ds, "Company")
                        With DataGridView1
                            .AutoGenerateColumns = True
                            .DataSource = ds
                            .DataMember = "Company"
                        End With

                        For Each dr As DataRow In ds.Tables("Company").Rows
                            List1.Items.Add(dr("CompName").ToString)
                            List1_1.Items.Add(dr("Counter"))
                        Next
                    End Using
                End Using

            Catch ex As Exception
                Debug.Print(ex.StackTrace & " - Load")
            End Try
        End Sub

        Private Function SelectCompany(lngID As Long) As Boolean
            '*************** ok
            strSql = "SELECT * FROM Company WHERE CLng(Counter) ="
            strSql = strSql & Chr(34) & lngID & Chr(34)

            dsCompany = New DataSet
            Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                conSchedules.Open()
                Using oledbAdapter As New OleDbDataAdapter(strSql, conSchedules)
                    oledbAdapter.Fill(dsCompany, "Company")
                End Using
            End Using

            If dsCompany.Tables("Company").Rows.Count > 0 Then
                Debug.Print(dsCompany.Tables("Company").Rows(0).Item("CompName").ToString & " - from Select")
                Return True
            Else
                Return False
            End If
        End Function

        Private Sub ShowData()
            '*************** ok
            If dsCompany.Tables("Company").Rows.Count > 0 Then
                txtCompany.Text = dsCompany.Tables("Company").Rows(0).Item("CompName").ToString
                txtMail.Text = dsCompany.Tables("Company").Rows(0).Item("CompEMail").ToString
                txtWeb.Text = dsCompany.Tables("Company").Rows(0).Item("CompURL").ToString

                ShowPicture()
            Else
                txtCompany.Text = ""
                txtMail.Text = ""
                txtWeb.Text = ""
            End If

        End Sub

        Private Sub SaveData()
            '*************** ok
            If Len(txtCompany.Text) <> 0 Then
                Try
                    Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                        conSchedules.Open()
                        strSql = "SELECT * FROM Company WHERE CLng(Counter) ="
                        strSql = strSql & Chr(34) & lngCurrent & Chr(34)
                        Dim daCompany As New OleDbDataAdapter(strSql, conSchedules)
                        dsCompany = New DataSet
                        daCompany.Fill(dsCompany, "Company")

                        ' edit the DataSet object
                        Dim dr As DataRow = dsCompany.Tables("Company").Rows(0)
                        dr("CompName") = txtCompany.Text
                        dr("CompEMail") = txtMail.Text
                        dr("CompURL") = txtWeb.Text

                        Dim objCommandBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(daCompany)
                        daCompany.Update(dsCompany, "Company")
                    End Using
                Catch ex As Exception
                    Debug.Print(ex.Message)
                End Try
            End If
        End Sub

        Private Sub List1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles List1.SelectedIndexChanged
            '*************** ok
            'when List1 index changes, update old values if necessary, and read new values
            SaveData()

            txtCompany.Text = Nothing
            txtMail.Text = Nothing
            txtWeb.Text = Nothing

            List1_1.SelectedIndex = List1.SelectedIndex

            lngCurrent = CLng(List1_1.SelectedItem)
            If SelectCompany(lngCurrent) Then
                ShowData()
            End If
        End Sub

        Private Sub cmdNewPic_Click(sender As System.Object, e As System.EventArgs) Handles cmdNewPic.Click
            'import a picture from disk into the database
            Try
                Dim result As DialogResult
                OpenFileDialog1.Filter = "JPEG Files (*.jpg)|*.jpg|Bitmap Files(*.bmp)|*.bmp| Gif files(*.gif)|*.gif"
                OpenFileDialog1.Multiselect = False
                result = OpenFileDialog1.ShowDialog
                If result = DialogResult.OK Then

                    PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)

                    Dim my_stream As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)
                    Dim bytes_stream(CInt(my_stream.Length) - 1) As Byte
                    my_stream.Read(bytes_stream, 0, bytes_stream.Length)

                    Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                        conSchedules.Open()
                        strSql = "SELECT * FROM Company WHERE CLng(Counter) ="
                        strSql = strSql & Chr(34) & lngCurrent & Chr(34)
                        Dim daCompany As New OleDbDataAdapter(strSql, conSchedules)
                        dsCompany = New DataSet
                        daCompany.Fill(dsCompany, "Company")

                        ' edit the DataSet object
                        Dim dr As DataRow = dsCompany.Tables("Company").Rows(0)
                        dr("CompLogo") = my_stream

                        Dim objCommandBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(daCompany)
                        daCompany.Update(dsCompany, "Company")
                    End Using
                End If
            Catch ex As Exception
                Debug.Write(ex.StackTrace)
            End Try
        End Sub

        Private Sub cmdDeletePic_Click(sender As System.Object, e As System.EventArgs) Handles cmdDeletePic.Click
            '*************** ok
            'delete the shown picture
            Dim Response As Integer = MessageBox.Show("Do you really want to delete this Company logo Picture ?", Me.Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
            If Response = 6 Then    '6 = Yes, 7 = No, 2 = Cancel
                Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                    conSchedules.Open()
                    strSql = "SELECT * FROM Company WHERE CLng(Counter) ="
                    strSql = strSql & Chr(34) & lngCurrent & Chr(34)
                    Dim daCompany As New OleDbDataAdapter(strSql, conSchedules)
                    dsCompany = New DataSet
                    daCompany.Fill(dsCompany, "Company")

                    ' edit the DataSet object
                    Dim drCurrent As DataRow = dsCompany.Tables("Company").Rows(0)
                    drCurrent("CompLogo") = Nothing
                    Dim objCommandBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(daCompany)
                    daCompany.Update(dsCompany, "Company")
                    PictureBox1.Image = Nothing
                End Using
            End If

        End Sub

        Private Sub ShowPicture()
            '*************** ok
            Dim dr As DataRow = dsCompany.Tables("Company").Rows(0)

            Try
                If dr("CompLogo").ToString = "" Then
                    PictureBox1.Image = Nothing
                    Exit Sub
                End If

                Dim bytImage() As Byte
                bytImage = CType(dr("CompLogo"), Byte())
                If bytImage Is Nothing Then Exit Sub
                Dim ms As New System.IO.MemoryStream(bytImage)
                Dim bytePic As New Bitmap(ms)
                ms.Close()
                PictureBox1.Image = bytePic
                PictureBox1.Refresh()
                Call StretchSourcePictureFromPicture(bytePic, PictureBox1)
                bytePic = Nothing

            Catch ex As Exception
                Debug.Print(ex.Message)
            End Try

        End Sub

        Private Sub cmdPastePic_Click(sender As System.Object, e As System.EventArgs) Handles cmdPastePic.Click

            'If image exists in the clipboard, paste it into the picture box
            If My.Computer.Clipboard.ContainsImage Then
                PictureBox1.Image = My.Computer.Clipboard.GetImage
                PictureBox1.Image.Save(My.Application.Info.DirectoryPath & "\TempPicture.bmp")

                Dim cn As New OleDbConnection
                Dim cmd As New OleDbCommand

                cn.ConnectionString = m_strSchedulesConnect
                cn.Open()
                cmd = cn.CreateCommand()
                cmd.CommandText = "SELECT * FROM Company WHERE CLng(Counter) = '" & CLng(List1_1.SelectedItem) & "'"
                Dim dr As OleDbDataReader = cmd.ExecuteReader

                Dim fs As FileStream = New FileStream(My.Application.Info.DirectoryPath & "\TempPicture.bmp", FileMode.Open, FileAccess.Read, FileShare.Read)
                Dim sr As StreamReader = New StreamReader(fs)
                Dim FileByteArray(CInt(fs.Length) - 1) As Byte
                fs.Read(FileByteArray, 0, CInt(fs.Length))
                cmd.Parameters.Add("@CompLogo", System.Data.OleDb.OleDbType.Binary, CInt(fs.Length)).Value = FileByteArray
                cmd.ExecuteNonQuery()
                cn.Close()
            Else
                MsgBox("The Clipbord does not contain any valid image!")
            End If
        End Sub

        Private Sub cmdCopyPic_Click(sender As System.Object, e As System.EventArgs) Handles cmdCopyPic.Click
            '*************** ok
            'Copy the picture from the picture box onto the clipboard
            My.Computer.Clipboard.Clear()
            My.Computer.Clipboard.SetImage(PictureBox1.Image)
        End Sub

        Private Sub StretchSourcePictureFromPicture(ByVal picSrc As Bitmap, ByVal picDest As PictureBox)
            '*************** ok
            On Error Resume Next
            Dim bm_source As Bitmap

            bm_source = picSrc

            Dim bm_dest As New Bitmap(CInt(picDest.Width), CInt(picDest.Height))
            Dim gr_dest As Graphics = Graphics.FromImage(bm_dest)

            gr_dest.DrawImage(bm_source, 0, 0, bm_dest.Width + 1, bm_dest.Height + 1)
            picDest.Image = bm_dest

        End Sub

        Private Sub cmdNewCompany_Click(sender As System.Object, e As System.EventArgs) Handles cmdNewCompany.Click
            '*************** ok
            SaveData()

            txtCompany.Text = Nothing
            txtMail.Text = Nothing
            txtWeb.Text = Nothing

            boolNewRecord = True
            txtCompany.Focus()
        End Sub

        Private Sub txtCompany_LostFocus(sender As Object, e As System.EventArgs) Handles txtCompany.LostFocus
            '*************** ok
            If boolNewRecord = True Then
                Try
                    If Len(txtCompany.Text) = 0 Then Exit Sub
                    Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                        conSchedules.Open()

                        strSql = "SELECT * FROM Company"

                        Using daCompany As New OleDbDataAdapter(strSql, conSchedules)
                            dsCompany = New DataSet
                            daCompany.MissingSchemaAction = MissingSchemaAction.AddWithKey
                            daCompany.Fill(dsCompany, "Company")

                            Dim newRow As DataRow = dsCompany.Tables("Company").NewRow()
                            newRow("CompName") = txtCompany.Text
                            dsCompany.Tables("Company").Rows.Add(newRow)

                            Dim myDataRowsCommandBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(daCompany)
                            daCompany.Update(dsCompany, "Company")
                        End Using
                    End Using

                    List1.Items.Clear()
                    List1_1.Items.Clear()

                    LoadData()

                    boolNewRecord = False
                Catch ex As Exception
                    Debug.Print(ex.StackTrace & " - txtCompany_LostFocus")
                End Try
            End If

        End Sub

        Private Sub cmdDeleteCompany_Click(sender As System.Object, e As System.EventArgs) Handles cmdDeleteCompany.Click
            '*************** ok
            Dim Response As Integer = MessageBox.Show("Do you really want to delete this Company ?", Me.Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
            If Response = 6 Then
                Try
                    strSql = "DELETE * from Company WHERE CLng(Counter) = '" & CLng(List1_1.SelectedItem) & "'"
                    Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                        conSchedules.Open()
                        Using dbCommand As OleDbCommand = New OleDb.OleDbCommand(strSql, conSchedules)
                            'delete the database table
                            dbCommand.ExecuteNonQuery()

                            'fill the ListBox once again
                            List1.Items.Clear()
                            List1_1.Items.Clear()
                            Dim ds As New DataSet
                            strSql = "SELECT * From Company ORDER BY CompName"
                            Using oledbAdapter As New OleDbDataAdapter(strSql, conSchedules)
                                oledbAdapter.Fill(ds, "Company")
                                For i As Integer = 0 To ds.Tables("Company").Rows.Count - 1
                                    List1.Items.Add(ds.Tables("Company").Rows(i).Item("CompName").ToString)
                                    List1_1.Items.Add(ds.Tables("Company").Rows(i).Item("Counter"))
                                Next
                            End Using
                        End Using
                    End Using
                Catch ex As Exception
                    Debug.Print(ex.StackTrace & " - cmdDeleteCompany")
                End Try
            End If
        End Sub

        Private Sub cmdItemPicShowScreen_Click(sender As System.Object, e As System.EventArgs) Handles cmdItemPicShowScreen.Click
            '*************** ok
            Try
                If Not PictureBox1.Image Is Nothing Then
                    PictureBox1.Image.Save(m_Path & "\TempPicture.bmp")
                    Dim strDocFile As String
                    strDocFile = m_Path & "\TempPicture.bmp"
                    Dim p As New System.Diagnostics.Process
                    p.StartInfo.FileName = strDocFile
                    p.Start()
                Else
                    Beep()
                    MsgBox("No Picture found !")
                    Exit Sub
                End If
            Catch ex As Exception
                Debug.Print(ex.Message)
            End Try
        End Sub
    End Class


    levesen

    Tuesday, October 16, 2012 8:52 PM
  • Levesen -- you don't say what's not working with your two subs. Can't offer much help if I don't know what problem you're having. Also, I suggest maybe starting another thread if this is no longer an ADO.NET issue (of course, without knowing the problem, I don't know whether it's an ADO.NET issue or not).

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Thursday, October 18, 2012 2:32 PM
  • Hi Bonnie,

    Hei,

    I got a problem when trying to import a disk picture into an access database using the ado.net. I got an error in the line: "If Cmd1.ShowDialog() = DialogResult.OK Then", and the error reads:

    System.AccessViolationException was unhandled
    Message=Trying to read or write to a protected memory. This is frequently  an indication of another destroyed memory (translated from Norwegian)
      Source=System.Windows.Forms  StackTrace:
           at System.Windows.Forms.FileDialogNative.IFileDialog.Show(IntPtr parent)
           at System.Windows.Forms.FileDialog.RunDialogVista(IntPtr hWndOwner)
           at System.Windows.Forms.FileDialog.RunDialog(IntPtr hWndOwner)
           at System.Windows.Forms.CommonDialog.ShowDialog(IWin32Window owner)
           at System.Windows.Forms.CommonDialog.ShowDialog()
           at WindowsApplication1.Form1.cmdNewPic_Click(Object sender, EventArgs e) in C:\VB_Net Programmer\Test_ADO_Net\WindowsApplication1\WindowsApplication1\Form1.vb:line  135
           at System.Windows.Forms.Control.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnClick(EventArgs e)
           at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
           at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
           at System.Windows.Forms.Control.WndProc(Message& m)
           at System.Windows.Forms.ButtonBase.WndProc(Message& m)
           at System.Windows.Forms.Button.WndProc(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
           at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
           at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
           at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
           at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
           at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
           at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
           at WindowsApplication1.My.MyApplication.Main(String[] Args) i 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
           at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
           at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
           at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
           at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
           at System.Threading.ExecutionContext.Run(ExecutionContext
    executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
           at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
           at System.Threading.ThreadHelper.ThreadStart()
      InnerException:

    The code:

    Private Sub cmdNewPic_Click(sender As System.Object, e As System.EventArgs) Handles cmdNewPic.Click

            'import a picture from disk into the database
            Try
                Dim Cmd1 As OpenFileDialog = New OpenFileDialog()
                If Cmd1.ShowDialog() = DialogResult.OK Then                         '************* error this line
                    PictureBox1.Image = Image.FromFile(Cmd1.FileName)

                    Dim my_stream As New FileStream(Cmd1.FileName, FileMode.Open, FileAccess.Read, FileShare.Read)
                    Dim bytes_stream(CInt(my_stream.Length) - 1) As Byte
                    my_stream.Read(bytes_stream, 0, bytes_stream.Length)

                    Using conSchedules As New OleDbConnection(m_strSchedulesConnect)
                        conSchedules.Open()
                        strSql = "SELECT * FROM Company WHERE CLng(Counter) ="
                        strSql = strSql & Chr(34) & lngCurrent & Chr(34)

                        Dim daCompany As New OleDbDataAdapter(strSql, conSchedules)
                        dsCompany = New DataSet
                        daCompany.Fill(dsCompany, "Company")

                        ' edit the DataSet object
                        Dim dr As DataRow = dsCompany.Tables("Company").Rows(0)
                        dr("CompLogo") = my_stream
                        Dim objCommandBuilder As OleDbCommandBuilder = New OleDbCommandBuilder(daCompany)
                        daCompany.Update(dsCompany, "Company")

                    End Using
                End If

            Catch ex As Exception
                Debug.Write(ex.StackTrace)
            End Try

        End Sub

    I have now spend a week trying to solve this problem to no avail, my other vb.net programs using this OpenFileDialog works perfectly.


    levesen

    Thursday, October 18, 2012 6:35 PM
  • I'm afraid that I can't help you with that error, levesen. I suggest you start another thread for that issue. And not here in the ADO.NET forum because it is clearly NOT an ADO.NET issue. You'll get more people looking at it too ...

    Sorry! =0(


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Saturday, October 20, 2012 1:08 AM
  • try to update with the same adapter you use for data retrieve without re-Instantiate it.
    Sunday, October 21, 2012 2:18 PM
  • That has nothing to do with the last problem that levesen needed help with.

    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Sunday, October 21, 2012 2:47 PM
  • Hi again there,

    Now I 'just' got one problem left, and that is import of a picture from disk to an Access database. Error still the same:

    System.AccessViolationException was unhandled
    Message=Trying to read or write to a protected memory. This is frequently  an indication of another destroyed memory (translated from Norwegian)

    and occurs when I try to read the OpenFileDialog:

    Dim Cmd1 As OpenFileDialog = New OpenFileDialog()
                If Cmd1.ShowDialog() = DialogResult.OK Then                         '************* error this line

    I would be very grateful if somebody could explain what to do to correct this problem!

    Kind regards
    Jorgen


    levesen

    Sunday, October 21, 2012 6:03 PM
  • Hi Jorgen,

    I thought I'd do a quick Google search, in case you hadn't or in case you missed something. I found something that might be helpful here:

    http://social.msdn.microsoft.com/Forums/en/vbgeneral/thread/4549c4ea-bbd2-486b-91a0-8791ab5d499d

    Basically, the guy says that he finally found the cause and a possible workaround. See if it applies to you:

    Ok I managed to pin down the problem:

    in the app the user is supposed to choose a company name from a combo connected to a datatable that is fed from an access DB

    according to the selection in the first combo a second combo is filled with data in the samw way

    this is the code:

    selval = cmb_company.SelectedValueoddaCat = New OleDb.OleDbDataAdapter("select category_Alias from categories where CompID = " & selval, conex)
    CBCat = New OleDb.OleDbCommandBuilder(oddaCat)
    oddaCat.Fill(DTCat)
    cmb_category.DataSource = DTCat
    cmb_category.DisplayMember = "category_Alias"

    after that the user presses a button that opens an openfiledialog

    thats when the error happens (on some computers not on all)

    BUT!!!

    if I first open the openfiledialog and afterward choose the combos then everything is OK

    I know I can just go Around the problem and first choose the file and afterward selected the combos

    but I would very much like to solve the problem since the procedural order is important


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com


    • Edited by BonnieBMVP Sunday, October 21, 2012 7:48 PM
    Sunday, October 21, 2012 7:45 PM
  • Hi again Bonnie,

    Yes, I have also seen this (together with 99 others similar), but contrary to the above my error occours at the first line in the Sub.

    Kind regards
    Jorgen


    levesen

    Monday, October 22, 2012 9:42 AM
  • I still think it's a similar situation as the other thread. The guys says that it happens (on some computers) after some ComboBoxes are filled from an Access database and it's happening in button click event *after* those ComboBoxes have been filled (from within in a different method I think). In other words, I'm pretty sure it's still very similar to your problem.

    Of course, he never really solved the problem, just had a workaround of some sort. Just to see if the problem lies with getting data from your Access database, can you at least try testing what he found by simulating the same sort of scenario in your app? Try commenting out all the code where you actually get data from your Access database, but still run the code with the FileOpenDialog() to see if will open then without an exception ...


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Monday, October 22, 2012 2:11 PM
  • Hei again Bonnie,

    I did as you suggested, commenting out all DataSet codes except the code in the "cmdNewPic_Click" sub. Now the FileOpenDialog() runs smootly without anny errors (jubi). That is a start, but where to go from here?

    Kind regards
    Jorgen


    levesen

    Tuesday, October 23, 2012 8:13 PM
  • Hi Jorgen,

    What to do about it is a good question. At least you now know that it has something to do with connecting to your Access database and that the issue is the exact same one that the guy in the other thread was having. I can think of two options:

    1) Reply to that other thread and ask the OP (Danielicy) if the problem was ever solved.

    2) Take this over to the Access forum (http://social.msdn.microsoft.com/Forums/en-US/accessdev/threads). Start another thread over there and post links to both this thread and to Danielicy's thread.

    Good luck and let us know if you get an answer!


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Tuesday, October 23, 2012 8:25 PM
  • It look like I somehow have solved the problem, please see the thread: http://social.msdn.microsoft.com/Forums/en-US/accessdev/thread/e3d5aed2-786a-4996-9de6-91d18eab4e57/?prof=required

    levesen

    • Marked as answer by levesen Wednesday, October 24, 2012 3:05 PM
    Wednesday, October 24, 2012 3:05 PM
  • Wow, seems odd that replacing all the "using" with "Dim" and specifically having to close the connection would fix the problem! The "using" is supposed to dispose the connection object at the end of the using block (and supposedly when disposing a connection it is closes it first).

    The guy in the other thread that I linked to earlier said it only happened on some computers, not all. I wonder if it's an issue with the OleDbConnection class or the OleDb provider you're using for your Access database? Probably the provider, but I don't use Access at all, so I don't know really ...

    But, at least you got that problem fixed! Yay!


    ~~Bonnie Berent DeWitt [C# MVP]

    geek-goddess-bonnie.blogspot.com

    Wednesday, October 24, 2012 3:36 PM