Imports System.Data.SqlClient
Imports System.ComponentModel
Imports System.Reflection


Public Class frmKundenblatt
    '  Public superuser As Boolean = False
    Dim KUNDE As VERAG_PROG_ALLGEMEIN.cKunde = Nothing
    Public kdNr As Integer
    Public FilialeNr As Integer = -1
    Dim kundenSQL As New kundenSQL
    Private bindingLKW As New BindingSource
    Private dataAdapterLKW As New SqlDataAdapter
    Dim lkwKzChange As New List(Of VERAG_PROG_ALLGEMEIN.MyListItem)
    ' Dim KUNDE As cKunde = Nothing
    Dim ADRESSE As VERAG_PROG_ALLGEMEIN.cAdressen = Nothing

    '  Public BERECHTIGUNEN As List(Of cBerechtigungen) = Nothing

    '  Private dataAdapterFirma As New SqlDataAdapter
    '  Private dataFirma As New DataTable
    'Private bindingFirma As New BindingSource
    Public showEdit As Boolean = False
    Private bindingSDL As New BindingSource
    Private dataAdapterSDL As New SqlDataAdapter

    'Dim cDATENSERVER As New VERAG_PROG_ALLGEMEIN.cDATENSERVER
    Private PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll
    ' Dim acd As List(Of cAutoCompleteData) = kundenSQL.getKundenShort()

    Private loaded As Boolean = False
    Dim gridReady As Boolean = True

    Dim SQL As New SQL
    Dim cSqlDb As New cSqlDb
    Dim FUNC As New cProgramFunctions

    ' INFO:
    Private InfoDauer As Integer = 3
    Private WithEvents timShow As New Timer With {.Interval = 10}
    Private WithEvents timHide As New Timer With {.Interval = 10}

    Private Sub frmKundenblatt_BackColorChanged(sender As Object, e As EventArgs) Handles pnl.BackColorChanged
        'lblFirma.BackColor = sender.BackColor
        '  pnl.BackColor = sender.BackColor
        ' KdSearchBox1.BackColor = sender.BackColor
        mne.BackColor = sender.BackColor
        For Each i As ToolStripMenuItem In mne.Items
            i.BackColor = sender.backcolor
        Next
        lblAbfVerb.BackColor = sender.backcolor
    End Sub

    Sub changeTab(index As Integer, tsi As ToolStripItem, Optional subItemIndexMDM As Integer = -1, Optional subItemIndexZoll As Integer = -1)
        If kdNr <= 0 Then
            If index <> 1 Then
                Exit Sub 'Kein Wechsel --> Kundenerfassung
            Else

            End If
        End If
        tbcntrMain.Visible = False


        'Vorher, damit flackern unterdrückt wird
        If subItemIndexMDM >= 0 Then tbcntrMDM.SelectedIndex = subItemIndexMDM
        If subItemIndexZoll >= 0 Then tbcntrZOLL.SelectedIndex = subItemIndexZoll

        tbcntrMain.SelectedIndex = index

        Dim RegularFont = New Font(mne.Font.FontFamily, mne.Font.Size, FontStyle.Regular)
        Dim RegularFontSub = New Font(mne.Font.FontFamily, 8.25, FontStyle.Regular)
        Dim BoldFont = New Font(tsi.Font.FontFamily, tsi.Font.Size, FontStyle.Underline Or FontStyle.Regular)

        For Each i As ToolStripItem In mne.Items
            i.Font = RegularFont
        Next
        tsi.Font = BoldFont

        '   tbItLeistungen.Font = RegularFontSub
        '   tbItKartenverwaltung.Font = RegularFontSub
        '  tbItLKW.Font = RegularFontSub
        ' tbItVERAGCard.Font = RegularFontSub
        tbcntrMain.Visible = True
    End Sub

    Private Sub frmKundenblatt_Load(sender As Object, e As EventArgs) Handles Me.Load
        'TabControl1.ItemSize = New Size(0, 0)
        ' Me.TabControl1.Visible = False
        tbcntrMain.Appearance = TabAppearance.FlatButtons
        tbcntrMain.ItemSize = New Size(0, 1)
        tbcntrMain.SizeMode = TabSizeMode.Fixed

        If FilialeNr > 0 Then
            UsrcntlKundeBearbeitenFull1.Filiale = FilialeNr
        End If
        'UsrcntlKundeBearbeitenFull1.BERECHTIGUNEN = BERECHTIGUNEN
        Me.KeyPreview = True
        pnlInfo.Height = 0
        KdSearchBox1.initKdBox(Me)
        AddHandler KdSearchBox1.PropertyChanged, Sub()
                                                     Try
                                                         ' If KdSearchBox1.KdNr <= 0 Then
                                                         '     tabindex = 0
                                                         ' End If


                                                         'Exit Sub
                                                         ' kdNr = KdSearchBox1.KdNr_value
                                                         ' initDataBinding()
                                                         '  Dim tabindex = Me.tbcntrMain.SelectedIndex
                                                         Dim tabindex = Me.tbcntrMain.SelectedIndex
                                                         Me.KUNDE = Nothing
                                                         Me.kdNr = KdSearchBox1.KdNr_value
                                                         initKUNDE() '  Me.frmKundenblatt_Load(Me, New EventArgs)
                                                         '  Me.initAllgemein()
                                                         ' If Me.tbcntrMain.SelectedIndex = 0 Then

                                                         ' Else
                                                         '      Me.tbcntrMain.SelectedIndex = 0
                                                         'End If
                                                         ' Me.tbcntrMain.SelectedIndex = 0
                                                         changeTab(tabindex, AllgemeinToolStripMenuItem)
                                                         TabControl1_TabIndexChanged(tbcntrMain, New EventArgs)

                                                     Catch ex As Exception
                                                         MsgBox(ex.Message & vbNewLine & ex.StackTrace)
                                                     End Try
                                                 End Sub
        KdSearchBox1.KdNr = kdNr ' Ruft initKUNDE auf

        changeTab(0, AllgemeinToolStripMenuItem)

        tbcntrMDM.TabPages.Remove(tbVERAGCard) 'Jetzt in SDL LEintstungen

        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", "SDL") Then
            FlatButton2.Enabled = False
            Button14.Enabled = False
            cboSDLLeistungen.Enabled = False
            Button12.Enabled = False
            Button5.Enabled = False
            Button6.Enabled = False
            Button15.Enabled = False

        End If



        loaded = True

        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "IMEX"
                ToolStripMenuItem4.Visible = False
            Case "ATILLA"
                ToolStripMenuItem4.Visible = False
        End Select

    End Sub

    Sub initKUNDE()
        
        If IsNumeric(kdNr) AndAlso kdNr >= 0 Then

            Try
                '  If IO.File.Exists("F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & ".jpg") Then : picLogo.ImageLocation = "F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & ".jpg"
                '   ElseIf IO.File.Exists("F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & ".BMP") Then : picLogo.ImageLocation = "F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & ".BMP"
                '  ElseIf IO.File.Exists("F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & ".GIF") Then : picLogo.ImageLocation = "F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & ".GIF"
                ' ElseIf IO.File.Exists("F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & ".PNG") Then : picLogo.ImageLocation = "F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & ".PNG"
                '  End If
                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("GRAFIK", "FIRMENLOGOS", "", "", "", kdNr, kdNr)

                Dim path = DS.GET_TOP1_PATH 'cDATENSERVER.getTOP1Path("GRAFIK", "FIRMENLOGOS", kdNr)
                If path <> "" Then
                    picLogo.ImageLocation = path
                End If
            Catch ex As Exception

            End Try
            initTABSDL_Allgemein()

            btnUpdateLKW.Enabled = False



            'KUNDE = Nothing
            Try
                KUNDE = New VERAG_PROG_ALLGEMEIN.cKunde(kdNr) 'kundenSQL.getKundeByKdNr(kdNr)
                ADRESSE = New VERAG_PROG_ALLGEMEIN.cAdressen(kdNr) 'kundenSQL.getKundeByKdNr(kdNr)
            Catch ex As Exception
                frmMain.setInfo("err", "Das Kundenblatt konnte nicht geladen werden.", 3)
                Me.Close()
            End Try
            '  MsgBox(kdNr & " _ " & KUNDE.Abfertigungsverbot)
            If KUNDE.Abfertigungsverbot Then
                lblAbfVerb.Visible = True
                btnAbfVerb.Text = "Abfertigungsverbot aufheben"
                pnl.BackColor = Color.FromArgb(200, 50, 50)
            Else
                lblAbfVerb.Visible = False
                btnAbfVerb.Text = "Abfertigungsverbot setzen"
                pnl.BackColor = Color.FromArgb(0, 54, 128) '(20, 114, 188)
            End If


            If ADRESSE.Auswahl = "I" Then ' If KUNDE.Auswahl = "I" Then
                lblINAKTIV.Visible = True
            Else
                lblINAKTIV.Visible = False

            End If



        Else
            UsrcntlKundeBearbeitenFull1.Enabled = False
            tbcntrMain.TabPages(2).Enabled = True
            initTABSDL_Firmendaten()

        End If
        ' lblFirma.Text = KUNDE.Kurzname
    End Sub
    Private Sub TabControl1_TabIndexChanged(sender As Object, e As EventArgs) Handles tbcntrMain.SelectedIndexChanged, tbcntrMDM.SelectedIndexChanged
        ' tbcntrMDM.SuspendLayout()
        '  If kdNr <= 0 Then changeTab(0, AllgemeinToolStripMenuItem) : Exit Sub
        If kdNr <= 0 Then changeTab(1, ToolStripMenuItem2) : Exit Sub

        If Me.loaded Then ' wenn fertig
            '  lblKdnr.Text = "KdNr: " & kdNr
            Select Case tbcntrMain.SelectedTab.Name
                Case "tbAllgemein" : initTABSDL_Allgemein()
                Case "tbFirmendaten" : initTABSDL_Firmendaten()
                Case "tbMdm"
                    Select Case tbcntrMDM.SelectedTab.Name
                        Case "tbLKW" : initTABLKW()
                        Case "tbSDL" : initTABSDL_Leistungen()
                        Case "tbVERAGCard" : initTABVERAGCard()
                        Case "tbSDLKarten" : initTABSDLDATEN()
                        Case "tbDokumente"
                            scanVertragVeragKd.INIT(kdNr, "KUNDENDATEN")
                            scanBankGarantie.INIT(kdNr, "KUNDENDATEN")
                            scanPersonalAusweisGF.INIT(kdNr, "KUNDENDATEN")
                            scanHRA.INIT(kdNr, "KUNDENDATEN")
                            scanHKA.INIT(kdNr, "KUNDENDATEN")
                            scanEULizenz.INIT(kdNr, "KUNDENDATEN")
                            scanSonstiges.INIT(kdNr, "KUNDENDATEN")
                            scanUebernahmebestätigungen.INIT(kdNr, "KUNDENDATEN", "Übernahmebestätigungen")
                        Case "tbBesuchsberichte" : initTABBesuchsberichte()
                    End Select
                Case "tbZoll" : initTZOLL()
                Case "tbOfferte" : UsrCntlOfferte1.init(kdNr)
                
            End Select
        End If
        'tbcntrMDM.ResumeLayout()
    End Sub

    Sub initTABSDL_Allgemein()
        ' dgvSDLLeistungen.Columns.Clear()
        dgvOfferte.Columns.Clear()
        initDgvOfferte()
        showDgvOfferte()
        initDgvSperrliste()

        ' initDgvSDLLeistungen()
        'showDgvSDLLeistungen()

        initAllgemein()
    End Sub

    Sub initTABSDL_Firmendaten()
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("Kundendaten_bearbeiten", Me) = 0 Then
            tbcntrMain.TabPages(1).Enabled = False
            ' cProgramFunctions.setAllReadOnly(Panel4)

        End If
        tbcntrMain.TabPages(1).Enabled = True
        UsrcntlKundeBearbeitenFull1.Enabled = True

        '  If kdNr > 0 Then

        'Dim usr As New usrcntlKundeBearbeitenFull(kdNr)

        UsrcntlKundeBearbeitenFull1.init(kdNr)

        If FilialeNr > 0 Then
            UsrcntlKundeBearbeitenFull1.cboFiliale.changeItem(FilialeNr)
        End If
        'End If
    End Sub

    Sub initTABVERAGCard()
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("MDM_VERAG_Card", Me) = 0 Then
            tbcntrMain.TabPages(4).Enabled = False
            ' cProgramFunctions.setAllReadOnly(Panel4)
        End If
        Dim usrcntlTMP As New usrCntlVERAGCard
        usrcntlTMP.displayFilter = False
        usrcntlTMP.onlyKdNr = True
        usrcntlTMP.Dock = DockStyle.Fill
        usrcntlTMP.kdnr = kdNr
        tbVERAGCard.Controls.Clear()
        tbVERAGCard.Controls.Add(usrcntlTMP)
    End Sub
    Sub initTABBesuchsberichte()
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("MDM_Besuchsberichte", Me) = 0 Then

            Dim usrcntlTMP As New usrCntlBesuchsberichte
            ' usrcntlTMP.displayFilter = False
            ' usrcntlTMP.onlyKdNr = True
            usrcntlTMP.Dock = DockStyle.Fill
            usrcntlTMP.kdnr = kdNr
            tbBesuchsberichte.Controls.Clear()
            tbBesuchsberichte.Controls.Add(usrcntlTMP)
        End If
    End Sub
    Sub initTABSDLDATEN()
        If False Then

            tbSDLKarten.Visible = False

            If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", "SDL") Then
                tbcntrMain.TabPages(5).Enabled = False
                ' cProgramFunctions.setAllReadOnly(Panel4)
            End If
            Dim usrcntlTMP As New usrCntlKartenDaten
            usrcntlTMP.SuspendLayout()
            usrcntlTMP.Visible = False
            usrcntlTMP.kdNr_filter = True
            usrcntlTMP.kdNr = kdNr

            usrcntlTMP.Dock = DockStyle.Fill
            tbSDLKarten.Controls.Clear()
            tbSDLKarten.Controls.Add(usrcntlTMP)

            tbSDLKarten.Visible = True
            usrcntlTMP.Visible = True
            usrcntlTMP.ResumeLayout()
        End If
        usrcntlKarten.kdNr_filter = True
        usrcntlKarten.kdNr = kdNr
        usrcntlKarten.init()
    End Sub

    Private Sub initTZOLL()
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("ZOLL_Hauptmenue", Me) = 0 Then
            If tbcntrZOLL.SelectedIndex = 0 Then
                Dim usrcntlTMP As New usrCntlZollArtikel
                usrcntlTMP.displayFilter = False
                usrcntlTMP.Dock = DockStyle.Fill
                usrcntlTMP.kdnr = kdNr
                usrcntlTMP.parentKundenblatt = True
                tabZoll_Artikel.Controls.Clear()
                tabZoll_Artikel.Controls.Add(usrcntlTMP)
            End If
        Else
            '     tbcntrMain.TabPages(5).Enabled = False
            setInfo("info", "Sie sind für den Bereich Zoll nicht freigeschaltet.", 3)
            tbcntrMain.SelectedIndex = 0
        End If
    End Sub

    Sub initTABLKW(Optional kz As String = "")
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("MDM_LKW_bearbeiten", Me) = 0 Then
            tbcntrMain.TabPages(2).Enabled = False
            ' cProgramFunctions.setAllReadOnly(tabLKW)
        End If

        Me.dgvLKW.DataSource = Me.bindingLKW
        initLKWBinding()
        initDgvLKW()
        btnUpdateLKW.Enabled = False
        If kz <> "" Then
            For Each r As DataGridViewRow In dgvLKW.Rows
                If r.Cells("KfzKennzeichen").Value = kz Then
                    dgvLKW.ClearSelection()
                    r.Selected = True
                    dgvLKW_SelectionChanged(dgvLKW, New EventArgs)
                    dgvLKW.FirstDisplayedScrollingRowIndex = r.Index
                    dgvLKW.PerformLayout()

                    Exit For
                End If
            Next
        End If
        dgvLKW_SelectionChanged(Me, New EventArgs)

    End Sub
    Sub initTABSDL_Leistungen()
        '        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("MDM_Leistungen_bearbeiten", "SDL") = 0 Then
        'tbcntrMain.TabPages(3).Enabled = False
        'End If
        ' cProgramFunctions.setAllReadOnly(tabLKW)
        getPartnerKdNrFromFMZOLL()
        Me.dgvSDLLeistungenFull.DataSource = Me.bindingSDL
        initdgvSDLLeistungenFull()
        showdgvSDLLeistungenFull()
        dgvSDLLeistungenFull_SelectionChanged(dgvSDLLeistungenFull, New EventArgs)
        ' If KUNDE IsNot Nothing Then rtbVermerke.Text = KUNDE.Vermerk
        'btnUpdateSDL.Enabled = False

    End Sub

    Sub initdgvSDLLeistungenFull()
        'Dim d As New SqlDataAdapter()
        Try
            Dim connectionString As String = cSqlDb.GetSDLConnectionString
            Dim sqlstr As String = " SELECT KundenSDL.SDLNr, Speditionsdienstleistungen.SDLBez,[Sperre], [Sperrdatum], [Vertretungsvollmacht], [Auszahlungsvollmacht], [Finanzamtbestätigung], [Antragsdatum],[Vermerk],  KundenSDL.[Erfassungsdatum], KundenSDL.[Änderungsdatum],KundenSDL.[Sachbearbeiter] " & _
                                   " FROM KundenSDL INNER JOIN Speditionsdienstleistungen ON Speditionsdienstleistungen.SDLNr=KundenSDL.SDLNr WHERE KundenSDL.KundenNr='" & kdNr & "' AND [SDLTypNr] <=2 ORDER BY Sperre,Speditionsdienstleistungen.SDLBez "
            Me.dataAdapterSDL = New SqlDataAdapter(sqlstr, connectionString)
        Catch ex As SqlException
            MessageBox.Show("Der Connection-String kann nicht verarbeitet werden. Wenden Sie sich an den Programmbetreuer.")
        End Try
        Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapterSDL)
        Dim table As New DataTable()
        Me.dataAdapterSDL.Fill(table)
        'table.Columns("KundenNr").DefaultValue = kdNr
        table.Locale = System.Globalization.CultureInfo.InvariantCulture
        bindingSDL.DataSource = table


        ' dgvSDLLeistungenFull.DataSource = sql.loadDgvBySql("SELECT KundenSDL.SDLNr, Speditionsdienstleistungen.SDLBez,[Sperre], [Sperrdatum], [Vertretungsvollmacht], [Auszahlungsvollmacht], [Finanzamtbestätigung], [Antragsdatum],[Vermerk],  KundenSDL.[Erfassungsdatum], KundenSDL.[Änderungsdatum],KundenSDL.[Sachbearbeiter] FROM KundenSDL,Speditionsdienstleistungen WHERE KundenSDL.KundenNr='" & kdNr & "' AND  Speditionsdienstleistungen.SDLNr=KundenSDL.SDLNr ")
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs)
        Try
            Me.dataAdapterSDL.Update(CType(Me.bindingSDL.DataSource, DataTable))
            ' btnUpdateSDL.Enabled = False
        Catch ex As Exception
            MsgBox(ex.Message, "Es ist ein Fehler aufgetreten:")
        End Try
    End Sub

    Private Sub dgvSDLLeistungenFull_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSDLLeistungenFull.CellValueChanged
        ' btnUpdateSDL.Enabled = True
        If e.ColumnIndex <> 9 And e.ColumnIndex <> 10 And e.ColumnIndex <> 11 Then
            Try
                dgvSDLLeistungenFull.Rows(e.RowIndex).Cells(11).Value = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME

                If dgvSDLLeistungenFull.Rows(e.RowIndex).Cells(9).Value.ToString = "" Then ' Neueintrag
                    dgvSDLLeistungenFull.Rows(e.RowIndex).Cells(9).Value = Now.ToString("dd.MM.yyyy HH:mm")
                Else 'Änderung
                    dgvSDLLeistungenFull.Rows(e.RowIndex).Cells(10).Value = Now.ToString("dd.MM.yyyy HH:mm")
                End If

            Catch ex As Exception
            End Try
        End If
    End Sub
    Private Sub dgvSDLLeistungenFull_UserDeletedRow(sender As Object, e As DataGridViewRowEventArgs) Handles dgvSDLLeistungenFull.UserDeletedRow
        'btnUpdateSDL.Enabled = True
    End Sub
    Sub getPartnerKdNrFromFMZOLL()
        PartnerKdNrFromFMZOLL = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)
    End Sub
    Sub showdgvSDLLeistungenFull(Optional selectedSDLLeistung As Integer = -1)
        With dgvSDLLeistungenFull
            .RowTemplate.Height = 20
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .RowTemplate.ReadOnly = True
            .RowHeadersVisible = False
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect

            .AllowUserToOrderColumns = True

            .Columns(0).Width = 50
            .Columns(0).HeaderText = "Nr"
            .Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns(1).Width = 180
            .Columns(1).HeaderText = "Bezeichnung"

            .Columns(2).Width = 50
            .Columns(2).HeaderText = "Sperre"

            .Columns(3).Width = 80
            .Columns(3).HeaderText = "Sperrdatum"

            .Columns(4).Width = 60
            .Columns(4).HeaderText = "Vertr.VM"

            .Columns(5).Width = 60
            .Columns(5).HeaderText = "Ausz.VM"

            .Columns(6).Width = 60
            .Columns(6).HeaderText = "FA.Best."

            .Columns(7).Width = 120
            .Columns(7).HeaderText = "Antragsdatum (FA)"

            .Columns(8).MinimumWidth = 100
            .Columns(8).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns(8).HeaderText = "Vermerk"

            .Columns(9).Visible = False
            .Columns(10).Visible = False
            .Columns(11).Visible = False

            .ClearSelection()
            For Each r As DataGridViewRow In .Rows
                If r.Cells("Sperre").Value IsNot DBNull.Value AndAlso r.Cells("Sperre").Value > 0 Then
                    r.DefaultCellStyle.ForeColor = Color.Red
                Else
                    'r.Cells("SperrBez").Value = ""
                End If
                If r.Cells("Sperre").Value IsNot DBNull.Value AndAlso r.Cells("Sperre").Value = selectedSDLLeistung Then
                    r.Selected = True
                End If
            Next
            If .RowCount > 0 And .SelectedRows.Count = 0 Then
                .Rows(0).Selected = True
            End If
        End With

    End Sub

    Sub initStat()
        lblStat_Lkws.Text = SQL.getSqlCount("SELECT Count(KfzKennzeichen) FROM LKW WHERE KundenNr=" & kdNr & " ") & " LKWs registriert"
        lblStat_SdlLeistungen.Text = SQL.getSqlCount("SELECT Count(SDL.SDLNr) FROM SDL, Speditionsdienstleistungen WHERE KundenNr=" & kdNr & " AND  SDL.SDLNr=Speditionsdienstleistungen.SDLNr ") & " SDL Leistungen"

        lblStat_SdlLeistungen_Diesel.Text = SQL.getSqlCount("SELECT Count(SDL.SDLNr) FROM SDL, Speditionsdienstleistungen WHERE KundenNr=" & kdNr & " AND  SDL.SDLNr=Speditionsdienstleistungen.SDLNr AND SDL.SDLNr IN (100,101)") & " Tankkarten"
        lblStat_SdlLeistungen_Maut.Text = SQL.getSqlCount("SELECT Count(SDL.SDLNr) FROM SDL, Speditionsdienstleistungen WHERE KundenNr=" & kdNr & " AND  SDL.SDLNr=Speditionsdienstleistungen.SDLNr AND SDL.SDLNr BETWEEN 200 AND 212 ") & " Mautboxen/-karten"

    End Sub
    Function checkNullStr(o As Object) As String
        If Not IsDBNull(o) Then
            Return o
        End If
        Return ""
    End Function

    Function checkNullBool(o As Object) As Boolean
        Try
            Return DirectCast(o, Boolean)
        Catch ex As Exception
            Return False
        End Try
    End Function
    ' Dim WithEvents oBinding As Binding


    Sub binddata(o As Object, bindingParam As String, bindingSource As BindingSource, dataName As String, Optional bindingNullValue As String = "")
        o.DataBindings.Clear()
        o.DataBindings.Add(New Binding(bindingParam, bindingSource, dataName, True, DataSourceUpdateMode.OnPropertyChanged, bindingNullValue))
    End Sub
    Public Sub initB(b As Binding, bindingSource As BindingSource, bindingParam As String, bindingDBname As String)
        If Not b Is Nothing Then Me.DataBindings.Remove(b)
        b = New Binding(bindingParam, bindingSource, bindingDBname)
        Me.DataBindings.Add(b)
    End Sub





    Sub initAllgemein()

        Try
            If kdNr > 0 Then
                KUNDE = New VERAG_PROG_ALLGEMEIN.cKunde(kdNr) 'kundenSQL.getKundeByKdNr(kdNr)
                ADRESSE = New VERAG_PROG_ALLGEMEIN.cAdressen(kdNr) 'kundenSQL.getKundeByKdNr(kdNr)

                'Me.dataAdapterFirma = Nothing
                ' Me.dataFirma.Clear()
                'SDL!
                ' KUNDE = New cKunde(kdNr)
                ' ADRESSE = New cAdressen(kdNr)
                Dim conn As SqlConnection = cSqlDb.GetNewOpenConnectionFMZOLL()
                ' Me.= New SqlDataAdapter("SELECT TOP 1 * FROM Adressen WHERE AdressenNr=" & kdNr, conn)
                ' Me.dataAdapterFirma.Fill(Me.dataFirma)
                conn.Close()

                'Me.dataFirma.AcceptChanges()
                ' Me.dataFirma.Locale = System.Globalization.CultureInfo.InvariantCulture


                lblKurzname.Text = checkNullStr(ADRESSE.Ordnungsbegriff)
                lblFirmenname1.Text = checkNullStr(ADRESSE.Name_1)
                lblFirmenname2.Text = checkNullStr(ADRESSE.Name_2)

                lblStrasse.Text = checkNullStr(ADRESSE.Straße)
                lblLandPlzOrt.Text = checkNullStr(ADRESSE.LandKz) & " - " & checkNullStr(ADRESSE.PLZ) & " - " & checkNullStr(ADRESSE.Ort)

                lblPostfach.Text = checkNullStr(ADRESSE.PLZPF) & " - " & checkNullStr(ADRESSE.Postfach)


                lblTel.Text = checkNullStr(ADRESSE.Telefon)
                lblFax.Text = checkNullStr(ADRESSE.Telefax)
                lblMobil.Text = checkNullStr(ADRESSE.Mobiltelefon)
                lblEmail.Text = checkNullStr(ADRESSE.E_Mail)
                lblEmail2.Text = checkNullStr(ADRESSE.E_Mail2)

                lblUid.Text = ""
                If checkNullStr(ADRESSE.UstIdGeprüft) <> "" Then
                    lblUid.Text = "UId: " & checkNullStr(ADRESSE.UstIdKz) & checkNullStr(ADRESSE.UstIdNr)
                    If checkNullStr(ADRESSE.UstIdGeprüft) <> "" Then
                        lblUid.Text &= " , geprüft am: " & checkNullStr(ADRESSE.UstIdGeprüft)
                    End If
                End If

            End If

        Catch ex As Exception
            MsgBox("Es ist ein Fehler beim Laden der Firmendaten - Allgemein aufgetreten!" & vbNewLine & vbNewLine & ex.Message & ex.StackTrace)
        End Try

    End Sub





    Sub playInfoSound()
        'Try : My.Computer.Audio.Play(My.Resources.chimes2, AudioPlayMode.Background) '"c:\Windows\Media\chimes.wav")
        'Catch ex As Exception : End Try
    End Sub
    Sub playErrorSound()
        'Try : My.Computer.Audio.Play(My.Resources.chimes2, AudioPlayMode.Background)
        'Catch ex As Exception : End Try
    End Sub





    Public Sub setInfo(art As String, text As String, dauer As Integer)

        pnlInfo.Height = 0
        If art.ToLower = "info" Then
            playInfoSound()
            InfoDauer = dauer
            txtInfotext.Text = text
            txtInfotext.Left = (pnlInfo.Width / 2) - (txtInfotext.Width / 2)
            timShow.Enabled = True
            pnlInfo.BackColor = Color.FromArgb(255, 255, 128)
            pnlInfo.ForeColor = Color.Black
        End If
        If art.ToLower = "err" Then
            playErrorSound()
            InfoDauer = dauer
            txtInfotext.Text = text
            txtInfotext.Left = (pnlInfo.Width / 2) - (txtInfotext.Width / 2)
            timShow.Enabled = True
            pnlInfo.BackColor = Color.FromArgb(255, 100, 100)
            pnlInfo.ForeColor = Color.FromArgb(255, 255, 255)
        End If
    End Sub

    Private Sub tim_Tick(sender As Object, e As EventArgs) Handles timShow.Tick
        If pnlInfo.Height >= 50 Then
            timShow.Enabled = False
            Wait(InfoDauer * 1000)
            timHide.Enabled = True
        Else
            pnlInfo.Height = pnlInfo.Height + 1
        End If
    End Sub
    Private Sub timHide_Tick(sender As Object, e As EventArgs) Handles timHide.Tick
        If pnlInfo.Height <= 0 Then
            timHide.Enabled = False
        Else
            pnlInfo.Height = pnlInfo.Height - 1
        End If
    End Sub
    Sub Wait(ByVal milliseconds As Integer)
        For x = 1 To milliseconds
            System.Threading.Thread.Sleep(1)
            Application.DoEvents()
        Next
    End Sub






    Sub initDgvOfferte()
        dgvOfferte.DataSource = SQL.loadDgvBySql("SELECT Offertenstamm.OffertenNr, Offertenstamm.OffertenBez FROM Kunden,Offerten,Offertenstamm WHERE Offerten.KundenNr=" & kdNr & " AND Kunden.KundenNr=Offerten.KundenNr AND Offertenstamm.OffertenNr=Offerten.OffertenNr ")
    End Sub



    ' Sub initDgvSDLLeistungen()

    '     dgvSDLLeistungen.DataSource = SQL.loadDgvBySql("SELECT KundenSDL.SDLNr, Speditionsdienstleistungen.SDLBez FROM KundenSDL,Speditionsdienstleistungen WHERE KundenSDL.KundenNr=" & kdNr & " AND  Speditionsdienstleistungen.SDLNr=KundenSDL.SDLNr ")
    'showDgvOfferte()
    ' End Sub



    Sub showDgvOfferte()
        With dgvOfferte
            .RowTemplate.Height = 20
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .RowTemplate.ReadOnly = True
            .RowHeadersVisible = False
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect

            .AllowUserToOrderColumns = True

            .Columns(0).Width = 50
            .Columns(0).HeaderText = "Nr"
            .Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns(1).Width = 230
            .Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns(1).HeaderText = "Bezeichnung"
        End With

    End Sub

    Sub initDgvOfferteOptions()

        With dgvOfferte
            Dim btnDel As New DataGridViewButtonColumn
            '   btnDel.DefaultCellStyle = "Löschen"
            If .ColumnCount = 3 Then
                '   .Columns.RemoveAt(3)
            End If
            .Columns.Add(btnDel)
            .Columns(2).Width = 50
            .Columns(2).HeaderText = "Löschen"

            For Each r As DataGridViewRow In .Rows
                '   r.Cells(2).Value = "test"
            Next

        End With
    End Sub


    Private Sub initLKWBinding()

        ' dgvLKW.DataSource = bindingLKW
        Dim d As New SqlDataAdapter()
        Try
            Dim connectionString As String = cSqlDb.GetSDLConnectionString

            Dim sqlstr As String = "SELECT KundenNr,KfzKennzeichen, Nationalität, Abgemeldet, Verkauft,KZAenderung, Vermerk,Erfassungsdatum,Änderungsdatum,Sachbearbeiter,Baujahr,[KzFinanzierungBank],[KzLeasing],[KzMiete] FROM LKW WHERE KundenNr=" & kdNr & " "
            If TextBox11.Text <> "" Then sqlstr &= " AND KfzKennzeichen LIKE '" & TextBox11.Text & "%'" 'Suchparam
            ' MsgBox(sqlstr)
            Me.dataAdapterLKW = New SqlDataAdapter(sqlstr, connectionString)
        Catch ex As SqlException
            MessageBox.Show("Der Connection-String kann nicht verarbeitet werden. Wenden Sie sich an den Programmbetreuer.")
        End Try
        Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapterLKW)
        Dim table As New DataTable()
        Me.dataAdapterLKW.Fill(table)
        table.Columns("KundenNr").DefaultValue = kdNr
        table.Locale = System.Globalization.CultureInfo.InvariantCulture
        bindingLKW.DataSource = table

        AddHandler table.ColumnChanging, Sub(send As Object, ev As DataColumnChangeEventArgs)
                                             If ev.Column.ColumnName = "KfzKennzeichen" Then
                                                 'MsgBox(ev.ProposedValue) 'NEU
                                                 'MsgBox(ev.Row.Item("KfzKennzeichen").ToString())
                                                 lkwKzChange.Add(New VERAG_PROG_ALLGEMEIN.MyListItem(ev.Row.Item("KfzKennzeichen").ToString(), ev.ProposedValue))
                                             End If
                                         End Sub
    End Sub

    Sub initDgvLKW()
        With dgvLKW

            '.DataSource = SQL.loadDgvBySql("SELECT KfzKennzeichen, Nationalität, Abgemeldet, Verkauft, Vermerk FROM LKW WHERE KundenNr=" & kdNr & " ")
            .RowTemplate.Height = 20
            ' .AllowUserToAddRows = False
            ' .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            '  .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            ' .RowTemplate.ReadOnly = True
            '.RowHeadersVisible = False
            '   .SelectionMode = DataGridViewSelectionMode.FullRowSelect

            .AllowUserToOrderColumns = True

            .Columns("KundenNr").Visible = False
            .Columns("Baujahr").Visible = False
            .Columns("KzFinanzierungBank").Visible = False
            .Columns("KzLeasing").Visible = False
            .Columns("KzMiete").Visible = False


            .Columns("KfzKennzeichen").MinimumWidth = 100
            .Columns("KfzKennzeichen").HeaderText = "KFZ-Kennzeichen"
            .Columns("KfzKennzeichen").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns("Nationalität").Width = 35
            .Columns("Nationalität").HeaderText = "Nat."
            .Columns("Nationalität").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("Abgemeldet").Visible = False
            .Columns("Abgemeldet").Width = 80
            .Columns("Abgemeldet").HeaderText = "Abgemeldet"
            .Columns("Abgemeldet").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("Verkauft").Width = 40
            .Columns("Verkauft").HeaderText = "Verk."
            .Columns("Verkauft").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("KZAenderung").Width = 40
            .Columns("KZAenderung").HeaderText = "KZ.Änd."
            .Columns("KZAenderung").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("Vermerk").MinimumWidth = 100
            '  .Columns(5).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("Vermerk").HeaderText = "Vermerk"


            '.Columns(5).Visible = False
            .Columns("Erfassungsdatum").Visible = False
            .Columns("Änderungsdatum").Visible = False
            .Columns("Sachbearbeiter").Visible = False

            '.Columns(6).ReadOnly = True
            '.Columns(7).ReadOnly = True
            '.Columns(8).ReadOnly = True

            For Each r As DataGridViewRow In .Rows
                If (r.Cells("Verkauft").Value IsNot DBNull.Value AndAlso r.Cells("Verkauft").Value) Or
                 (r.Cells("Abgemeldet").Value IsNot DBNull.Value AndAlso r.Cells("Abgemeldet").Value) Or
                 (r.Cells("KZAenderung").Value IsNot DBNull.Value AndAlso r.Cells("KZAenderung").Value) Then
                    r.DefaultCellStyle.ForeColor = Color.Red
                End If

            Next
        End With


        lblErgebnisse.Text = "Ergebnisse: " & dgvLKW.Rows.Count ' - 1
    End Sub




    Private Sub InvoiceLinesDataGridView_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) Handles dgvOfferte.CellPainting
        'e.Graphics = New Graphics
        If e.ColumnIndex = 2 AndAlso e.RowIndex >= 0 Then
            e.Paint(e.CellBounds, DataGridViewPaintParts.All)

            Dim bmpFind As Bitmap = My.Resources.del
            ' Dim newImage As Image = New Bitmap(newWidth, newHeight)
            Dim ico As Icon = Icon.FromHandle(bmpFind.GetHicon)
            e.Graphics.DrawImage(bmpFind, e.CellBounds.Left + 15, e.CellBounds.Top + 3, 16, 16)
            e.Handled = True
        End If
    End Sub
    Private Sub InvoiceLines_CellPainting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs)
        'e.Graphics = New Graphics
        If e.ColumnIndex = 2 AndAlso e.RowIndex >= 0 Then
            e.Paint(e.CellBounds, DataGridViewPaintParts.All)

            Dim bmpFind As Bitmap = My.Resources.del
            ' Dim newImage As Image = New Bitmap(newWidth, newHeight)
            Dim ico As Icon = Icon.FromHandle(bmpFind.GetHicon)
            e.Graphics.DrawImage(bmpFind, e.CellBounds.Left + 15, e.CellBounds.Top + 3, 16, 16)
            e.Handled = True
        End If
    End Sub

    Sub initDgvSperrliste()
        With dgvSperrliste
            ' .DataSource = SQL.loadDgvBySql("SELECT Speditionsdienstleistungen.SDLNr,Speditionsdienstleistungen.SDLBez,Sperrnummernverzeichnis.SperrNr,Sperrnummernverzeichnis.SperrBez,KundenSDL.Sperrdatum  FROM Speditionsdienstleistungen,KundenSDL,Sperrnummernverzeichnis WHERE KundenSDL.KundenNr=" & kdNr & " AND Speditionsdienstleistungen.SDLNr=KundenSDL.SDLNr AND Sperrnummernverzeichnis.SperrNr=KundenSDL.Sperre /*AND KundenSDL.Sperrdatum IS NOT NULL*/ ORDER BY SperrNr")
            .DataSource = SQL.loadDgvBySql(" SELECT KundenSDL.SDLNr, Speditionsdienstleistungen.SDLBez,Sperrnummernverzeichnis.SperrNr,Sperrnummernverzeichnis.SperrBez, [Sperrdatum] " & _
                                            " FROM KundenSDL INNER JOIN Speditionsdienstleistungen ON Speditionsdienstleistungen.SDLNr=KundenSDL.SDLNr INNER JOIN Sperrnummernverzeichnis ON Sperrnummernverzeichnis.SperrNr=KundenSDL.Sperre " &
                                            " WHERE KundenSDL.KundenNr='" & kdNr & "' /*AND [SDLTypNr] <=2 */ ORDER BY Sperre,Speditionsdienstleistungen.SDLBez")
            .RowTemplate.Height = 20
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .RowTemplate.ReadOnly = True
            .RowHeadersVisible = False
            '.SelectionMode = DataGridViewSelectionMode.FullRowSelect
            ' .CanSelect = False
            .AllowUserToOrderColumns = True

            .Columns(0).Width = 45
            .Columns(0).HeaderText = "SDL-Nr"
            .Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns(1).MinimumWidth = 110
            .Columns(1).HeaderText = "SDL-Bezeichnung"
            .Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns(2).Width = 40
            .Columns(2).HeaderText = "Sperre"
            .Columns(2).DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns(3).Width = 110
            .Columns(3).HeaderText = "Sperr-Bezeichnung"

            .Columns(4).Width = 75
            .Columns(4).HeaderText = "Sperrdatum"
            .Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            initSDLListeRed()
        End With
    End Sub

    'initialisieren der Offerte-CBO 
    ' Private Sub initOfferte(sender As Object, e As EventArgs)
    'Dim offerte As List(Of cOffert) = kundenSQL.getOfferte()
    '     cboAddOffert.Items.Clear()
    '      For Each o In offerte
    ' ComboBox1.Items.Add(New (o.OffertenNr & " - " & o.OffertenBez, o.OffertenNr))
    '          cboAddOffert.Items.Add(New MyListItem(o.OffertenNr & " - " & o.OffertenBez, o.OffertenNr))
    '      Next
    '  End Sub


    Sub initSDLListeRed()
        For Each r As DataGridViewRow In dgvSperrliste.Rows
            If r.Cells("SperrNr").Value > 0 Then
                r.DefaultCellStyle.ForeColor = Color.Red
            Else
                r.Cells("SperrBez").Value = ""
            End If
        Next

    End Sub
    'Wenn ein Eintrag in der CBO ausgewählt wurde wird dieser in der DB eingetragen
    '  Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs)
    'Dim oItem As MyListItem = CType(cboAddOffert.SelectedItem, MyListItem)
    '     kundenSQL.insertOffert(kdNr, oItem.Value)
    '      cboAddOffert.Items.Clear()
    '    dgvOfferte.Columns.Clear()
    '    initDgvOfferte()
    '  initDgvOfferteOptions()
    'End Sub

    'initialisieren der SDL-Leistungen-CBO 
    Private Sub initSDLLeistungenAdd(sender As Object, e As EventArgs) Handles cboSDLLeistungen.Click
        Dim offerte As List(Of cSpeditionsdienstleistungen) = kundenSQL.getSpeditionsdienstleistungen(True)
        sender.Items.Clear()
        For Each o In offerte
            sender.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem(o.SDLNr & " - " & o.SDLBez, o.SDLNr))
        Next
    End Sub

    'Wenn ein Eintrag in der CBO ausgewählt wurde wird dieser in der DB eingetragen
    Private Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSDLLeistungen.SelectedIndexChanged
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", "SDL") Then Exit Sub

        If MsgBox("Möchten Sie die Leistung '" & sender.text & "' hinzufügen?", MsgBoxStyle.YesNo) = vbYes Then
            Dim oItem As VERAG_PROG_ALLGEMEIN.MyListItem = CType(sender.SelectedItem, VERAG_PROG_ALLGEMEIN.MyListItem)
            kundenSQL.insertKundenSDL(kdNr, oItem.Value)
            sender.Items.Clear()
            'If sender.Name = "cboAddSDLLeistungen" Then
            ' dgvSDLLeistungen.Columns.Clear()
            ' initDgvSDLLeistungen()
            '  initDgvSDLLeistungenOptions()
            'End If
            ' If sender.Name = "cboSDLLeistungen" Then
            dgvSDLLeistungenFull.Columns.Clear()
            initdgvSDLLeistungenFull()
            showdgvSDLLeistungenFull(oItem.Value)
            Try

                For Each r As DataGridViewRow In dgvSDLLeistungenFull.Rows
                    If r.Cells("SDLNr").Value = oItem.Value Then
                        dgvSDLLeistungenFull.ClearSelection()
                        r.Selected = True
                        dgvSDLLeistungenFull_CellClick(dgvSDLLeistungenFull, New DataGridViewCellEventArgs(0, r.Index))
                    End If
                Next
            Catch ex As Exception

            End Try
            'End If
        End If
    End Sub

    'Löschen in der DGV dgvOfferte gelklickt?
    Private Sub dgvOfferte_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvOfferte.CellClick
        If e.ColumnIndex = 2 AndAlso e.RowIndex >= 0 Then
            If vbYes = MsgBox("Del: " & dgvOfferte.Rows(e.RowIndex).Cells(0).Value, vbYesNo) Then
                kundenSQL.delOffert(kdNr, dgvOfferte.Rows(e.RowIndex).Cells(0).Value)
            End If
            dgvOfferte.Columns.Clear()
            initDgvOfferte()
            showDgvOfferte()
        End If
    End Sub

    'Löschen in der DGV dgvSDLLeistungen gelklickt?
    ' Private Sub dgvSDLLeistungen_CellContentClick(sender As Object, e As DataGridViewCellEventArgs)
    '     If e.ColumnIndex = 2 AndAlso e.RowIndex >= 0 Then
    '        If vbYes = MsgBox("Del: " & dgvSDLLeistungen.Rows(e.RowIndex).Cells(0).Value, vbYesNo) Then
    '           kundenSQL.delKundenSDL(kdNr, dgvSDLLeistungen.Rows(e.RowIndex).Cells(0).Value)
    '      End If
    '     dgvSDLLeistungen.Columns.Clear()
    '    initDgvSDLLeistungen()
    '   showDgvSDLLeistungen()
    ' End If
    'End Sub

    'Keine Auswahl zulassen
    Private Sub dgv_SelectionChanged(sender As Object, e As EventArgs) Handles dgvOfferte.SelectionChanged, dgvSperrliste.SelectionChanged
        sender.ClearSelection()
    End Sub

    Private Sub dgvLKW_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvLKW.CellValueChanged
        btnUpdateLKW.Enabled = True
        If e.ColumnIndex <> 7 And e.ColumnIndex <> 8 And e.ColumnIndex <> 6 Then
            Try
                dgvLKW.Rows(e.RowIndex).Cells(8).Value = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME

                If dgvLKW.Rows(e.RowIndex).Cells(6).Value.ToString = "" Then ' Neueintrag
                    dgvLKW.Rows(e.RowIndex).Cells(6).Value = Now.ToString("dd.MM.yyyy HH:mm")
                Else 'Änderung
                    dgvLKW.Rows(e.RowIndex).Cells(7).Value = Now.ToString("dd.MM.yyyy HH:mm")
                End If

            Catch ex As Exception
            End Try
        End If
    End Sub

    Private Sub dgvLKW_UserDeletedRow(kdNr, newKfz, SDLNr, History) Handles UsrCntlLKW1.LKWChanged
        dgvLKW_SelectionChanged(dgvLKW, New EventArgs)
        '???????????
    End Sub

    Private Sub usrCntlLKW_Button2() Handles UsrCntlLKW1.nextLKW_Clicked
        If dgvLKW.SelectedRows.Count > 0 Then
            Dim i As Integer = dgvLKW.SelectedRows(0).Index
            If (i + 1 < dgvLKW.RowCount) Then
                dgvLKW.ClearSelection()
                dgvLKW.Rows(i + 1).Selected = True
                dgvLKW_SelectionChanged(dgvLKW, New EventArgs)
            End If
        End If
    End Sub

    Private Sub usrCntlLKW_Button1() Handles UsrCntlLKW1.prevLKW_Clicked
        If dgvLKW.SelectedRows.Count > 0 Then
            Dim i As Integer = dgvLKW.SelectedRows(0).Index
            If (i > 0) Then
                dgvLKW.ClearSelection()
                dgvLKW.Rows(i - 1).Selected = True
                dgvLKW_SelectionChanged(dgvLKW, New EventArgs)
            End If
        End If
    End Sub



    Private Sub dgvLKW_SelectionChanged(sender As Object, e As EventArgs) Handles dgvLKW.Click ', dgvLKW.CellContentClick
        If Not gridReady Then Exit Sub
        '  MsgBox("SEL!!!!")
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", "SDL") Then FlatButton2.Enabled = (dgvLKW.SelectedCells.Count > 0)


        If dgvLKW.SelectedRows.Count > 0 AndAlso dgvLKW.Rows(0).Cells(1).Value IsNot DBNull.Value Then
            Dim nat = ""
            Try : nat = dgvLKW.SelectedRows(0).Cells(2).Value
            Catch : End Try
            UsrCntlLKW1.init(kdNr, dgvLKW.SelectedRows(0).Cells("KfzKennzeichen").Value, dgvLKW.SelectedRows(0).Cells("Nationalität").Value, dgvLKW.SelectedRows(0).Cells("Erfassungsdatum").Value, dgvLKW.SelectedRows(0).Cells("Änderungsdatum").Value, dgvLKW.SelectedRows(0).Cells("Sachbearbeiter").Value)

        End If
    End Sub


    Private Sub btnUpdateLKW_Click(sender As Object, e As EventArgs) Handles btnUpdateLKW.Click
        Try
            '    For Each row As DataRow In CType(Me.bindingLKW.DataSource, DataTable).Rows
            'If row.RowState = DataRowState.Modified Then
            'MsgBox(row.Item("KfzKennzeichen"))
            '   Exit For
            '   End If
            '   Next

            If Me.dataAdapterLKW.Update(CType(Me.bindingLKW.DataSource, DataTable)) > 0 Then
                For Each i In lkwKzChange
                    If i.Text <> "" Then
                        'MsgBox(i.Text & " >> " & i.Value)
                        SQL.doSQL("UPDATE SDL SET KfzKennzeichen='" & i.Value & "' WHERE KundenNr='" & kdNr & "' AND KfzKennzeichen='" & i.Text & "'", "SDL", True)
                    End If
                Next
            End If

            btnUpdateLKW.Enabled = False
        Catch ex As Exception
            MsgBox("Es ist ein Fehler aufgetreten: " & ex.Message)
        End Try

    End Sub

    Private Sub TextBox11_TextChanged(sender As Object, e As EventArgs) Handles TextBox11.TextChanged
        gridReady = False
        initLKWBinding()
        initDgvLKW()
        gridReady = True
        dgvLKW_SelectionChanged(dgvLKW, New EventArgs)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        TextBox11.Text = ""
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        initLKWBinding()
        initDgvLKW()
    End Sub




    Private Sub lblStat_Lkws_Click(sender As Object, e As EventArgs) Handles lblStat_Lkws.Click
        tbcntrMain.SelectedIndex = 2
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        If GroupBox5.Visible Then 'Stat angezeigt
            GroupBox5.Visible = False
            sender.text = "Statistik anzeigen"
            picLogo.Visible = True
        Else
            GroupBox5.Visible = True
            initStat()
            sender.text = "Statistik ausblenden"
            picLogo.Visible = False
        End If

    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles btnAbfVerb.Click
        If KUNDE.Abfertigungsverbot Then
            If vbYes = MsgBox("Möchten Sie wirklich ein Abfertigungsverbot aufheben?", MsgBoxStyle.YesNoCancel) Then
                kundenSQL.setAbfertigungsverbot(kdNr, False)
                Me.KUNDE = Nothing
                Me.kdNr = kdNr
                Me.frmKundenblatt_Load(Me, New EventArgs)
                Me.tbcntrMain.SelectedIndex = 0
            End If
        Else
            If vbYes = MsgBox("Möchten Sie wirklich ein Abfertigungsverbot setzten?", MsgBoxStyle.YesNoCancel) Then
                kundenSQL.setAbfertigungsverbot(kdNr, True)
                Me.KUNDE = Nothing
                Me.kdNr = kdNr
                Me.frmKundenblatt_Load(Me, New EventArgs)
                Me.tbcntrMain.SelectedIndex = 0
            End If
        End If

    End Sub

    Private Sub Label2_Click(sender As Object, e As EventArgs) Handles Label2.Click
        tbcntrMain.SelectedIndex = 3
    End Sub



    Private Sub dgvSDLLeistungenFull_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSDLLeistungenFull.CellClick
        If dgvSDLLeistungenFull.SelectedRows.Count > 0 Then
            If Not dgvSDLLeistungenFull.SelectedRows(0).Cells(9).Value Is DBNull.Value Then lblErfassungsdatum_SDL.Text = dgvSDLLeistungenFull.SelectedRows(0).Cells(9).Value
            If Not dgvSDLLeistungenFull.SelectedRows(0).Cells(10).Value Is DBNull.Value Then lblAenderungsdatum_SDL.Text = dgvSDLLeistungenFull.SelectedRows(0).Cells(10).Value
            If Not dgvSDLLeistungenFull.SelectedRows(0).Cells(11).Value Is DBNull.Value Then lblLetzterSA_SDL.Text = dgvSDLLeistungenFull.SelectedRows(0).Cells(11).Value
        End If
    End Sub

    Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", "SDL") Then Exit Sub

        If dgvSDLLeistungenFull.SelectedRows.Count > 0 Then
            If vbYes = MsgBox("Möchten Sie die Leistung wirklich löschen? " & vbNewLine & vbNewLine & dgvSDLLeistungenFull.SelectedRows(0).Cells("SDLNr").Value & " - " & dgvSDLLeistungenFull.SelectedRows(0).Cells("SDLBez").Value, vbYesNo) Then
                kundenSQL.delKundenSDL(kdNr, dgvSDLLeistungenFull.SelectedRows(0).Cells(0).Value)
            End If

            dgvSDLLeistungenFull.Columns.Clear()
            initdgvSDLLeistungenFull()
            showdgvSDLLeistungenFull()

        End If

    End Sub

    Private Sub dgvSDLLeistungenFull_SelectionChanged(sender As Object, e As EventArgs) Handles dgvSDLLeistungenFull.SelectionChanged
        Panel2.Visible = False
        grpMautDE.Visible = False

        scanJaraVereinbarung.Visible = False
        '  scanJaraVertretung.Visible = False
        scanErstbestellung.Visible = False
        scanMWSTAgreement.Visible = False

        If dgvSDLLeistungenFull.SelectedRows.Count > 0 Then
            Panel2.Visible = True
            'Scan-Elemente initialisieren:
            Dim tmpSDLNr = dgvSDLLeistungenFull.SelectedRows(0).Cells("SDLNr").Value
            scanErstbestellung.INIT(kdNr, "MDM_Leistung", "SDL_" & tmpSDLNr)
            scanJaraVereinbarung.INIT(kdNr, "MDM_Leistung", "SDL_" & tmpSDLNr)
            scanMWSTAgreement.INIT(kdNr, "MDM_Leistung", "SDL_" & tmpSDLNr)
            '   scanJaraVertretung.INIT(kdNr, "MDM_Leistung", "SDL_" & tmpSDLNr)
            scanSDLSonst.INIT(kdNr, "MDM_Leistung", "SDL_" & tmpSDLNr)

            Select Case tmpSDLNr
                Case 100 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.IDSKundenNr 'IDS
                Case 200 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.ATKundenNr 'AT
                Case 212 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.UTAKundenNr 'UTA
                Case 101 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.WölflKundenNr 'WÖLFL
                Case 202 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.TELEPASS_Kd_Nr 'TELEPASS
                Case 214, 215, 216 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.PLOSE_KundenNr 'PLOSE

                Case 201 : grpMautDE.Visible = True : Panel2.Visible = False 'MAUT DE
                    txtMautDE_FlottenPIN.Text = PartnerKdNrFromFMZOLL.MautDE_FlottenPIN 'MAUT DE
                    txtMautDEMasterPIN.Text = PartnerKdNrFromFMZOLL.MautDE_MasterPIN 'MAUT DE
                    txtMautDE_BenutzerNr.Text = PartnerKdNrFromFMZOLL.MautDE_BenutzerNr 'MAUT DE
                Case 203, 204, 206, 207, 208, 209, 211, 205, 213 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.MSEKundenNr 'MSE 205??
                Case 210, 500 : Panel2.Visible = False
                Case Else : Panel2.Visible = False : Exit Sub
            End Select

            Select Case tmpSDLNr
                Case 202
                    scanJaraVereinbarung.Visible = True
                    '     scanJaraVertretung.Visible = True
                    scanErstbestellung.Visible = True
                Case 203 : scanErstbestellung.Visible = True
                Case 209 : scanErstbestellung.Visible = True
                Case 215 : scanErstbestellung.Visible = True' PLOSE IT
                Case 214 : scanErstbestellung.Visible = True 'PLOSE Roadmaster
                Case 211
                    '    scanErstbestellung.Visible = True
                    scanMWSTAgreement.Visible = True
                    ' Case 100 : scanErstbestellung.Visible = True
                    '  Case 212 : scanErstbestellung.Visible = True

                Case Else : Exit Sub
            End Select
        End If
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click, Button15.Click
        If dgvSDLLeistungenFull.SelectedRows.Count > 0 Then
            Dim sdlNrTmp = dgvSDLLeistungenFull.SelectedRows(0).Cells(0).Value
            Select Case sdlNrTmp
                Case 100 : kundenSQL.setPartnerKdNrFromFMZOLL_IDS(kdNr, txtPartnerKdNr.Text) 'IDS :
                    'gibt keine Einträge
                Case 200 : kundenSQL.setPartnerKdNrFromFMZOLL_AT(kdNr, txtPartnerKdNr.Text) 'AT
                    kundenSQL.setPartnerKdNrSDL("KartenNr", txtPartnerKdNr.Text, kdNr, sdlNrTmp)  'UTA
                Case 212 : kundenSQL.setPartnerKdNrFromFMZOLL("UTAKundenNr", txtPartnerKdNr.Text, kdNr)  'UTA
                    kundenSQL.setPartnerKdNrSDL("CLIENT-Nr", txtPartnerKdNr.Text, kdNr, sdlNrTmp)  'UTA
                Case 101 : kundenSQL.setPartnerKdNrFromFMZOLL("WölflKundenNr", txtPartnerKdNr.Text, kdNr) 'WÖLFL
                    'gibt keine Einträge
                Case 202 : kundenSQL.setPartnerKdNrFromFMZOLL("TELEPASS-Kd-Nr", txtPartnerKdNr.Text, kdNr) 'TELEPASS
                    kundenSQL.setPartnerKdNrSDL("TELEPASS-Kd-Nr", txtPartnerKdNr.Text, kdNr, sdlNrTmp)
                Case 214, 215, 216 : kundenSQL.setPartnerKdNrFromFMZOLL("PLOSEKundenNr", txtPartnerKdNr.Text, kdNr) 'PLOSE
                Case 201 : kundenSQL.setPartnerKdNrFromFMZOLL_DE(kdNr, txtMautDE_FlottenPIN.Text, txtMautDEMasterPIN.Text, txtMautDE_BenutzerNr.Text)
                    kundenSQL.setPartnerKdNrSDL("FlottenPIN", txtMautDE_FlottenPIN.Text, kdNr, sdlNrTmp)
                    kundenSQL.setPartnerKdNrSDL("MasterPIN", txtMautDEMasterPIN.Text, kdNr, sdlNrTmp)
                    kundenSQL.setPartnerKdNrSDL("BenutzerNr", txtMautDE_BenutzerNr.Text, kdNr, sdlNrTmp)
                Case 203, 204, 206, 207, 208, 209, 210, 211, 205, 213 : kundenSQL.setPartnerKdNrFromFMZOLL("MSEKundenNr", txtPartnerKdNr.Text, kdNr) 'MSE 205?? 
                    kundenSQL.setPartnerKdNrSDL("MSE-Kd-Nr", txtPartnerKdNr.Text, kdNr, sdlNrTmp)
                Case Else : Exit Sub
            End Select
            getPartnerKdNrFromFMZOLL()
        End If
    End Sub

    Dim delSdlClickValue As Integer = -1
    Private Sub sender(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs)
        Try
            If e.Button = Windows.Forms.MouseButtons.Right Then
                sender.ClearSelection()
                sender.Rows(e.RowIndex).Selected = True
                ContextMenuStrip2.Show(sender, sender.PointToClient(Cursor.Position))
                delSdlClickValue = e.RowIndex
            End If
        Catch ex As Exception
            ' MsgBox(ex.Message)
        End Try
    End Sub

    Dim delOfferteClickValue As Integer = -1
    Private Sub dgvOfferte_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvOfferte.CellMouseDown
        Try
            If e.Button = Windows.Forms.MouseButtons.Right Then
                sender.ClearSelection()
                sender.Rows(e.RowIndex).Selected = True
                ContextMenuStrip3.Show(sender, sender.PointToClient(Cursor.Position))
                delOfferteClickValue = e.RowIndex
            End If
        Catch ex As Exception
            '  MsgBox(ex.Message)
        End Try
    End Sub

    'Private Sub LöschenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LöschenToolStripMenuItem.Click
    'If delSdlClickValue >= 0 Then
    '    If vbYes = MsgBox("Möchten Sie die Leistung '" & dgvSDLLeistungen.Rows(delSdlClickValue).Cells(0).Value() & " - " & dgvSDLLeistungen.Rows(delSdlClickValue).Cells(1).Value() & "' wirklich löschen?", vbYesNo) Then
    'kundenSQL.delKundenSDL(kdNr, dgvSDLLeistungen.Rows(delSdlClickValue).Cells(0).Value())
    'dgvSDLLeistungen.Columns.Clear()
    'initDgvSDLLeistungen()
    'showDgvSDLLeistungen()
    'End If
    'delSdlClickValue = -1
    'End If
    'End Sub

    Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
        MsgBox("NICHT ERLAUBT!")
        ' If delOfferteClickValue >= 0 Then
        'If vbYes = MsgBox("Möchten Sie die Leistung '" & dgvOfferte.Rows(delOfferteClickValue).Cells(0).Value() & " - " & dgvOfferte.Rows(delOfferteClickValue).Cells(1).Value() & "' wirklich löschen?", vbYesNo) Then
        'kundenSQL.delOffert(kdNr, dgvOfferte.Rows(delOfferteClickValue).Cells(0).Value())
        ' End If

        ' delOfferteClickValue = -1
        ' End If
    End Sub



    ' DGV mit CRTL+S speichern
    Private Sub Form1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles Me.KeyDown
        If dgvLKW.Focused Or (Not dgvLKW.EditingControl Is Nothing AndAlso dgvLKW.EditingControl.Focused) Then ' wenn DGV fokusiert, oder in Bearbeitung
            If e.Modifiers = Keys.Control Then
                If e.KeyCode = Keys.S Then
                    dgvLKW.EndEdit() ' Falls noch in Bearbeitung
                    btnUpdateLKW.PerformClick() ' Speichern 
                End If
            End If
        End If
        If e.KeyCode = Keys.Escape Then
            KdSearchBox1.SelectAll()
            KdSearchBox1.Focus()
        End If
    End Sub



    Private Sub rtbVermerke_TextChanged(sender As Object, e As EventArgs) Handles rtbVermerke.Leave
        kundenSQL.setVermerke(rtbVermerke.Text, KUNDE.KundenNr)
        initKUNDE()
    End Sub




    Private Sub dgvSDLLeistungenFull_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSDLLeistungenFull.CellDoubleClick
        Button12.PerformClick()
    End Sub

    Private Sub lblEmail_TextChanged(sender As Object, e As EventArgs) Handles lblEmail.MouseUp, lblEmail2.MouseUp
        If sender.SelectedText = "" Then System.Diagnostics.Process.Start("mailto:" & sender.text)
    End Sub


    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
        If dgvSDLLeistungenFull.SelectedRows.Count > 0 Then
            Dim frmSDLDetails As New frmSDLDetails
            frmSDLDetails.KdNr = kdNr
            frmSDLDetails.sdlNr = dgvSDLLeistungenFull.SelectedRows(0).Cells(0).Value
            Me.Enabled = False
            If frmSDLDetails.ShowDialog(Me) = vbOK Then
                initTABSDL_Leistungen()
            End If
            Me.Enabled = True
        End If
    End Sub


    Private Sub picLogo_Click(sender As Object, e As EventArgs) Handles picLogo.Click
        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("GRAFIK", "FIRMENLOGOS", "", "", "", kdNr, kdNr)
        Dim path = DS.uploadDataToDATENSERVERFileDialog(, , , "PIC")
        'Dim path = cDATENSERVER.uploadDataToDATENSERVERFileDialog("GRAFIK", "FIRMENLOGOS", kdNr, , , , "PIC")
        If path <> "" Then
            picLogo.ImageLocation = path
        End If


        Exit Sub
        Dim fd As OpenFileDialog = New OpenFileDialog()
        Dim strFileName As String
        Try
            If System.IO.Directory.Exists("F:\") Then
                If System.IO.Directory.Exists("F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\") Then
                    System.IO.Directory.CreateDirectory("F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\")
                Else
                    Exit Sub
                End If
            End If

            fd.Title = "Bild auswählen"
            fd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

            fd.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"
            fd.FilterIndex = 2
            fd.RestoreDirectory = True

            If fd.ShowDialog() = DialogResult.OK Then
                strFileName = "F:\PROGRAMME\SDL_DATA\FIRMENLOGOS\" & kdNr & System.IO.Path.GetExtension(fd.FileName)
                If kdNr > 0 Then
                    FileCopy(fd.FileName, strFileName)
                End If
                picLogo.ImageLocation = strFileName

            End If
        Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try
    End Sub

    Private Function cut_file(ByVal file As String) As String ' Funktion zum Entfernen der Backslashs / Ordner While file.Contains("\") file = file.Remove(0, 1) End While Return file End Function 
        While file.Contains("\")
            file = file.Remove(0, 1)
        End While
        Return file
    End Function


    Private Sub FlatButton1_Click(sender As Object, e As EventArgs)
        Dim kdsrch As New SDL.frmKundenSuche
        kdsrch.erweitern = True
        Me.Enabled = False
        If kdsrch.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
            Me.KUNDE = Nothing
            Me.kdNr = kdsrch.kundenNrSearch.Text
            Me.frmKundenblatt_Load(Me, New EventArgs)
            Me.initAllgemein()
            Me.tbcntrMain.SelectedIndex = 0
        End If
        Me.Enabled = True
    End Sub


    Private Sub AllgemeinToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AllgemeinToolStripMenuItem.Click

        changeTab(0, sender)

    End Sub

    Private Sub ToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem2.Click

        changeTab(1, sender)
    End Sub

    ' Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.DoubleClick
    '     changeTab(3, ToolStripMenuItem4, 0)
    ' changeTab(3, sender)
    'End Sub

    Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
        changeTab(3, sender, 1)
    End Sub

    Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem5.Click

        changeTab(2, sender)
    End Sub

    Private Sub tbitVERAGCard_Click(sender As Object, e As EventArgs)
        changeTab(3, ToolStripMenuItem4, 3)
    End Sub

    Private Sub tbitLeistungen_Click(sender As Object, e As EventArgs)
        changeTab(3, ToolStripMenuItem4, 0)
    End Sub

    Private Sub tbitKartenverwaltung_Click(sender As Object, e As EventArgs)
        changeTab(3, ToolStripMenuItem4, 1)
    End Sub

    Private Sub tbitLKW_Click(sender As Object, e As EventArgs)
        changeTab(3, ToolStripMenuItem4, 2)
    End Sub

    Private Sub DropDownOpened(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.DropDownOpened
        ToolStripMenuItem4.DropDownDirection = ToolStripDropDownDirection.BelowLeft

    End Sub


    Private Sub FlatButton2_Click(sender As Object, e As EventArgs)
        Me.WindowState = FormWindowState.Minimized
    End Sub

    Private Sub FlatButton1_Click_1(sender As Object, e As EventArgs)
        Me.Close()
    End Sub



    Private Sub FlatButton1_Click(sender As Object, e As MouseEventArgs) Handles Button13.MouseClick ', Button13.Click
        sender.ContextMenuStrip = cntxtExcel
        sender.ContextMenuStrip.Show(sender, e.Location)
        ' FlatButton1.ContextMenuStrip.Show()
    End Sub

    Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click
        Me.Cursor = Cursors.WaitCursor
        cProgramFunctions.genExcelFromDGV(dgvLKW, True)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub ToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem6.Click
        Me.Cursor = Cursors.WaitCursor
        cProgramFunctions.genExcelFromDGV_NEW(dgvLKW, True)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub dgvLKW_RowHeaderMouseDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvLKW.CellDoubleClick
        Dim frmGrayOut = cProgramFunctions.grayoutForm(Me)
        Dim l As New frmLKWDetails(dgvLKW.Rows(e.RowIndex).Cells("KundenNr").Value, dgvLKW.Rows(e.RowIndex).Cells("KfzKennzeichen").Value)
        If l.ShowDialog(frmGrayOut) = DialogResult.OK Then
            initTABLKW()
        End If
        frmGrayOut.Close()
    End Sub

    Private Sub Button14_Click(sender As Object, e As EventArgs) Handles Button14.Click
        Dim frmGrayOut = cProgramFunctions.grayoutForm(Me)
        Dim l As New frmLKWDetails(kdNr, "", True)
        If l.ShowDialog(frmGrayOut) = DialogResult.OK Then
            initTABLKW(l.txtKennzeichen.Text)
        End If
        frmGrayOut.Close()
    End Sub

    Private Sub FlatButton2_Click_1(sender As Object, e As EventArgs) Handles FlatButton2.Click
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", "SDL") Then Exit Sub
        If dgvLKW.SelectedRows.Count > 20 Then MsgBox("Es können nicht mehr als 20 Zeilen gelöscht werden!") : Exit Sub
        If dgvLKW.SelectedRows.Count = 0 Then Exit Sub
        Dim txt As String = "Möchten Sie den Eintrag / die Einträge wirklich löschen?" & vbNewLine & vbNewLine
        For Each r As DataGridViewRow In dgvLKW.SelectedRows
            txt &= r.Cells("KfzKennzeichen").Value & vbNewLine
        Next
        If vbYes = MsgBox(txt, vbYesNoCancel) Then
            For Each r As DataGridViewRow In dgvLKW.SelectedRows
                Dim kdTMP = r.Cells("KundenNr").Value
                Dim kfzKzTMP = r.Cells("KfzKennzeichen").Value
                SQL.doSQL("DELETE TOP (1) FROM LKW WHERE KundenNr='" & kdTMP & "' AND  KfzKennzeichen='" & kfzKzTMP & "'", "SDL", True)
                 SQL.doSQL("DELETE FROM SDL WHERE KundenNr='" & kdTMP & "' AND  KfzKennzeichen='" & kfzKzTMP & "' and SDLNr <> '501' ", "SDL", True)
                usrCntlSDLLeistungVERAGCard.clearAllVeragCard(kdTMP, kfzKzTMP)
                'SQL.doSQL("UPDATE [Kartenpool] SET [KundenNr]=NULL, [KfzKennzeichen]=NULL, [Fahrer]=NULL, [Datum]=NULL, [Kaution]=NULL, [BelegNr]=NULL, [Ersatzkarte]=NULL, [Gesperrt]=0, [Defekt]=0, [Verloren]=0, [Gestohlen]=0, [Vermerk]='', [Änderungsdatum]='" & Now & "', [Sachbearbeiter]='" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME & "' WHERE KundenNr='" & kdTMP & "' AND  KfzKennzeichen='" & kfzKzTMP & "'", "SDL", True)
            Next
            initTABLKW()
        End If 'DEL
    End Sub

   
    Private Sub dgvLKW_KeyDown(sender As Object, e As KeyEventArgs) Handles dgvLKW.KeyUp
        If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Or e.KeyCode = Keys.End Or e.KeyCode = Keys.PageDown Or e.KeyCode = Keys.PageUp Then
            dgvLKW_SelectionChanged(Me, New EventArgs)
        End If
    End Sub

   
  
    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
        Me.Cursor = Cursors.WaitCursor
        'cProgramFunctions.genExcelFromDGV_NEW(dgvLKW, True)
        Dim Path = ""
        genLKWListeExcel(cProgramFunctions.dgridViewTods(dgvLKW), Path)
        If Path <> "" Then Process.Start(Path)
        Me.Cursor = Cursors.Default
    End Sub


    Shared Function genLKWListeExcel(dt As DataTable, ByRef Path As String) As Boolean
        Try

            If dt IsNot Nothing And dt.Rows.Count > 0 Then


                Dim sPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\LKWListe\" ' My.Computer.FileSystem.GetTempFileName
                If Not My.Computer.FileSystem.DirectoryExists(sPath) Then
                    My.Computer.FileSystem.CreateDirectory(sPath)
                End If


                Dim exclApp As Object 'as Application
                Dim Datei As Object 'as WorkBook
                Dim Blatt As Object 'Microsoft.Office.Interop.Excel.Worksheet 'As Object 'as Worksheet
                exclApp = CreateObject("Excel.Application")

                With exclApp
                    .Visible = False

                    Try
                        Path = sPath & "LKWListe_" & dt.Rows(0)("KundenNr") & ".xlsx"
                        While System.IO.File.Exists(Path)
                            Path = sPath & "LKWListe_" & dt.Rows(0)("KundenNr") & "_" & Now.ToString("ddMMyyyyHHmmss") & ".xlsx"
                        End While
                        My.Computer.FileSystem.WriteAllBytes(Path, My.Resources.LKW_Liste, False)
                    Catch ex As System.Exception
                        '  MsgBox(ex.Message)
                        MsgBox("ERROR 01: " & ex.Message & vbNewLine & ex.StackTrace)
                        Return False
                    End Try


                    Datei = .Workbooks.Open(Path) 'Anpassen
                    Blatt = Datei.Worksheets(1) 'Anpassen

                    Blatt.Range("L1").Value = Now.ToShortDateString
                    Dim cnt = 4
                    For Each r In dt.Rows
                        If cnt = 4 Then
                            Dim AD As New VERAG_PROG_ALLGEMEIN.cAdressen(r("KundenNr"))
                            Blatt.Range("D1").Value = r("KundenNr")
                            Blatt.Range("E1").Value = (AD.Name_1 & " " & If(AD.Name_2, "")).trim
                        End If

                        Blatt.Range("A" & cnt).Value = r("KundenNr")
                        Blatt.Range("B" & cnt).Value = r("KfzKennzeichen")
                        Blatt.Range("C" & cnt).Value = r("Nationalität")
                        Blatt.Range("D" & cnt).Value = VERAG_PROG_ALLGEMEIN.SQL.checkNullDateReturnValue(r("Baujahr"), "") 'If(r("Abgemeldet") IsNot DBNull.Value, CDate(r("Baujahr")).ToShortDateString, "")
                        Blatt.Range("E" & cnt).Value = If(VERAG_PROG_ALLGEMEIN.SQL.checkNullBool(r("Abgemeldet")), "x", "")
                        '  Blatt.Range("F" & cnt).Value = r("Kennzeichen")
                        Blatt.Range("G" & cnt).Value = If(VERAG_PROG_ALLGEMEIN.SQL.checkNullBool(r("KzMiete")), "x", "")
                        Blatt.Range("H" & cnt).Value = If(VERAG_PROG_ALLGEMEIN.SQL.checkNullBool(r("KzLeasing")), "x", "")
                        Blatt.Range("I" & cnt).Value = If(VERAG_PROG_ALLGEMEIN.SQL.checkNullBool(r("KzFinanzierungBank")), "x", "")
                        Blatt.Range("J" & cnt).Value = If(VERAG_PROG_ALLGEMEIN.SQL.checkNullBool(r("Verkauft")), "x", "")
                        Blatt.Range("K" & cnt).Value = If(VERAG_PROG_ALLGEMEIN.SQL.checkNullBool(r("KZAenderung")), "x", "")
                        Blatt.Range("L" & cnt).Value = r("Vermerk")

                        cnt += 1
                    Next
                    Datei.Save
                    Datei.Close()
                    Datei = Nothing
                    exclApp = Nothing

                End With

                Return True
            End If

        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Return False
    End Function
    Private Sub frmKundenblatt_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        If showEdit Then changeTab(1, ToolStripMenuItem2)

        If My.Computer.Screen.WorkingArea.Width * 0.8 > Me.MinimumSize.Width Then
            Me.Width = My.Computer.Screen.WorkingArea.Width * 0.8
            Me.Left = (My.Computer.Screen.WorkingArea.Width - Me.Width) / 2
        End If
        If My.Computer.Screen.WorkingArea.Height * 0.8 > Me.MinimumSize.Height Then
            Me.Height = My.Computer.Screen.WorkingArea.Height * 0.8
            Me.Top = (My.Computer.Screen.WorkingArea.Height - Me.Height) / 2
        End If
        Me.StartPosition = FormStartPosition.CenterScreen

    End Sub

    Private Sub ToolStripMenuItem7_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem7.Click

        changeTab(4, sender)
    End Sub

   
    Private Sub ToolStripMenuItem8_Click(sender As Object, e As EventArgs)

        changeTab(5, sender)
    End Sub

    Private Sub UsrCntlLKW1_Load(sender As Object, e As EventArgs) Handles UsrCntlLKW1.Load

    End Sub

    Private Sub dgvSDLLeistungenFull_CellContentClick_1(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSDLLeistungenFull.CellContentClick

    End Sub

    Private Sub txtPartnerKdNr_TextChanged(sender As Object, e As KeyEventArgs) Handles txtPartnerKdNr.KeyDown
        If e.KeyCode = Keys.Return Then
            Button6.PerformClick()
        End If
    End Sub

    Private Sub txtMautDE_BenutzerNr_TextChanged(sender As Object, e As KeyEventArgs) Handles txtMautDE_BenutzerNr.KeyDown, txtMautDEMasterPIN.KeyDown, txtMautDE_FlottenPIN.KeyDown
        If e.KeyCode = Keys.Return Then
            Button15.PerformClick()
        End If
    End Sub

    Private Sub UsrcntlKundeBearbeitenFull1_KD_SAVED(kdnrTMP As Object) Handles UsrcntlKundeBearbeitenFull1.KD_SAVED
        If Me.kdNr < 0 And kdnrTMP > 0 Then
            KdSearchBox1.KdNr = kdnrTMP
        End If
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim LIST As New List(Of String)
        For Each s In dgvLKW.SelectedRows
            LIST.Add(s.cells("KfzKennzeichen").value)
        Next
        Dim f As New frmLKW_AnhaengeDatenarchiv(kdNr, LIST)
        f.ShowDialog(Me)
    End Sub


End Class

