Imports System.Data.SqlClient

Public Class cBinding
    Public bindingDataAdapter As New SqlDataAdapter
    Public WithEvents bindingdataTable As New DataTable
    Public bindingdataSet As New DataSet
    Public WithEvents bindingSource As New BindingSource

    Dim connection As SqlConnection


    Public updateImmediately = False

    Sub New(Optional conn As String = "SDL")
        Select Case conn
            Case "SDL" : connection = cSqlDb.GetNewOpenConnection(False)
            Case "FMZOLL" : connection = cSqlDb.GetNewOpenConnectionFMZOLL(False)
        End Select
    End Sub



    Public Sub initBinding(sql, table)
        Try
            bindingSource.CancelEdit()
            '  bindingSource.ResetBindings(False)
            bindingSource = New BindingSource
            bindingdataTable.Clear()
            bindingdataTable = New DataTable(table)
            bindingdataTable.TableName = table
            bindingdataSet.Clear()

                Try
                    Me.bindingDataAdapter = New SqlDataAdapter(sql, connection)
                Catch ex As SqlException
                    MessageBox.Show("Der Connection-String kann nicht verarbeitet werden. Wenden Sie sich an den Programmbetreuer.")
                End Try
                Me.bindingDataAdapter.FillSchema(bindingdataSet, SchemaType.Source, table)
                Me.bindingDataAdapter.Fill(bindingdataSet, table)
                Me.bindingdataTable = Me.bindingdataSet.Tables(table)
                Me.bindingSource.DataSource = Me.bindingdataTable

                Me.bindingdataTable.Locale = System.Globalization.CultureInfo.InvariantCulture
        Catch ex As Exception
            MsgBox("BindingERR01: " & ex.Message)
        End Try
    End Sub

    Sub setARITHABORTOn()
        Try
           Using cmd As New SqlCommand("SET ARITHABORT ON", connection)
                cmd.ExecuteNonQuery()
            End Using
        Catch ex As Exception
            MsgBox("BindingERR02: " & "Fehler in setARITHABORTOn: " & ex.Message)
        End Try
    End Sub


    Public Sub newEntry(kdNr, kfz, sdlNr, Optional save = True)
        Try
            Dim SQL As New SQL
            Dim History = SQL.getValueTxtBySql("SELECT isnull(max([History]),0)+1 as History FROM SDL where KundenNr = '" & kdNr & "' And SDLNr ='" & sdlNr & "' ", "SDL")
            SQL.doSQL("INSERT INTO SDL (KundenNr,KfzKennzeichen,SDLNr,History,Bestelldatum) VALUES ('" & kdNr & "','" & kfz & "','" & sdlNr & "','" & History & "',GETDATE())")
            Exit Sub
            row_kdNr = kdNr
            row_kfz = kfz
            row_sdlNr = sdlNr

            Dim row = bindingdataTable.NewRow()
            bindingdataTable.Rows.Add(row)

            bindingSource.MoveLast()

            bindingSource.Position = bindingSource.Count - 1
            'If save Then updateBinding()
        Catch ex As Exception
            MsgBox("BindingERR03: " & ex.Message)
        End Try
    End Sub

    Public Function updateBinding(Optional tablename As String = "", Optional ContinueUpdateOnError As Boolean = False) As Boolean
        If tablename = "" Then tablename = bindingdataTable.TableName

        Try
            bindingSource.EndEdit() 'Beendet die Bearbeitung
            Dim modrows As Integer = 0
            For Each row As DataRow In bindingdataTable.Rows
                If row.RowState = DataRowState.Modified Then
                    ' MsgBox(": Es ist ei")
                    modrows += 1
                    Exit For
                End If
            Next
            Dim builder As New SqlCommandBuilder(bindingDataAdapter)
            bindingDataAdapter.ContinueUpdateOnError = ContinueUpdateOnError
            '  bindingDataAdapter.FillLoadOption = LoadOption.OverwriteChanges

            If Not modrows = bindingDataAdapter.Update(bindingdataSet, tablename) Then
                'MsgBox(tablename & ": Es ist ein SQL-Fehler beim Updaten der Daten aufgetreten!")
            End If
            Me.bindingdataSet.AcceptChanges()
            Return True
        Catch ex As Exception
            MsgBox("Es ist ein SQL-Fehler beim Updaten der Daten aufgetreten:" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & "Die Werte werden zurückgesetzt!", MsgBoxStyle.OkCancel, "Datenbank-Fehler")
            MsgBox(ex.StackTrace)
            Me.bindingSource.ResumeBinding()
        End Try
        Return False
    End Function


    Public Function updateBindingSicherung(Optional tablename As String = "") As Boolean
        If tablename = "" Then tablename = bindingdataTable.TableName
        Try

            bindingSource.EndEdit() 'Beendet die Bearbeitung
            Dim modrows As Integer = 0
            For Each row As DataRow In bindingdataTable.Rows
                If row.RowState = DataRowState.Modified Then
                    ' MsgBox(": Es ist ei")
                    modrows += 1
                    Exit For
                End If
            Next
            Dim builder As New SqlCommandBuilder(bindingDataAdapter)

            MsgBox(bindingDataAdapter.SelectCommand.CommandText)
            MsgBox(bindingDataAdapter.Update(bindingdataSet, tablename))
            If Not modrows = bindingDataAdapter.Update(bindingdataSet, tablename) Then
                '  MsgBox(tablename & ": Es ist ein SQL-Fehler beim Updaten der Daten aufgetreten!")
            End If

            Return True
        Catch ex As Exception
            MsgBox("Es ist ein SQL-Fehler beim Updaten der Daten aufgetreten:" & vbNewLine & vbNewLine & ex.Message & vbNewLine & vbNewLine & "Die Werte werden zurückgesetzt!", MsgBoxStyle.OkCancel, "Datenbank-Fehler")
            Me.bindingSource.ResetBindings(False)
        End Try
        Return False
    End Function

    Public row_kdNr As String = ""
    Public row_sdlNr As String = ""
    Public row_kfz As String = ""

    Public Sub bindingdataTable_TableNewRow_SDLLeistungen(sender As Object, e As DataTableNewRowEventArgs)
        Dim currentHisId = 0
        Try : currentHisId = sender.Select("History=MAX(History)")(0).Item("History") : Catch : End Try
        currentHisId += 1

        Dim kundenSQL As New kundenSQL
        Dim row As DataRow = e.Row
        row("KundenNr") = row_kdNr
        row("SDLNr") = row_sdlNr
        row("History") = currentHisId 'kundenSQL.getHoechsteHistoryNr(row_kdNr, row_sdlNr)
        row("KfzKennzeichen") = row_kfz
        Dim dt As DateTime = Now
        row("Bestelldatum") = dt
        '    row("Vermerk") = "test " & row("History")
        row("Erfassungsdatum") = Now
        row("Sachbearbeiter") = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME

        bindingSource.MoveLast()
    End Sub

    Public Sub bindingdataTable_TableNewRow_Adressen(sender As Object, e As DataTableNewRowEventArgs)
        Dim currentHisId = 0
        Try : currentHisId = sender.Select("History=MAX(History)")(0).Item("History") : Catch : End Try
        currentHisId += 1
        MsgBox(currentHisId)
        Dim kundenSQL As New kundenSQL
        Dim row As DataRow = e.Row
        row("KundenNr") = row_kdNr
        row("SDLNr") = row_sdlNr
        row("History") = currentHisId 'kundenSQL.getHoechsteHistoryNr(row_kdNr, row_sdlNr)
        row("KfzKennzeichen") = row_kfz
        ' row("Vermerk") = "test " & row("History")
        row("Erfassungsdatum") = Now
        row("Sachbearbeiter") = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME

        bindingSource.MoveLast()
    End Sub

    Sub binddata(o As Object, bindingParam As String, bindingSource As BindingSource, dataName As String, Optional bindingNullValue As String = "", Optional formatString As String = "")
        o.DataBindings.Clear()
        o.DataBindings.Add(New Binding(bindingParam, bindingSource, dataName, True, DataSourceUpdateMode.OnPropertyChanged, bindingNullValue, formatString))
        'DirectCast(o, Control).CausesValidation = True

    End Sub


    Private Sub bindingSource_DataError(sender As Object, e As BindingManagerDataErrorEventArgs) Handles bindingSource.DataError
        ' If the data source raises an exception when a cell value is 
        ' commited, display an error message.
        If e.Exception IsNot Nothing Then ' AndAlso  e. = DataGridViewDataErrorContexts.Commit Then
            MessageBox.Show("Daten-Fehler: " & vbNewLine & vbNewLine & e.Exception.Message)


        End If
    End Sub
  

    Private Sub bindingdataTable_ColumnChanged(sender As Object, e As DataColumnChangeEventArgs) Handles bindingdataTable.ColumnChanged
        If updateImmediately Then updateBinding()
    End Sub
End Class
