Imports System.Data.SqlClient
Imports System.Globalization
Imports System.Web.UI.WebControls.Expressions
Imports com.sun.xml.internal.rngom
Imports GrapeCity.Viewer.Common.Model
Imports Microsoft.Office.Interop
Imports VERAG_PROG_ALLGEMEIN


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
    Dim KUNDE_ERW As VERAG_PROG_ALLGEMEIN.cKundenErweitert = Nothing
    Dim KUNDE_K_RE As VERAG_PROG_ALLGEMEIN.cKundenKontakte = Nothing
    Dim KUNDE_K_GF As VERAG_PROG_ALLGEMEIN.cKundenKontakte = 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

    Dim RG_MONAT As Date = CDate("01." & Now.Month & "." & Now.Year) '.AddMonths(-1)
    ' INFO:
    Private InfoDauer As Integer = 3
    Private WithEvents timShow As New Timer With {.Interval = 10}
    Private WithEvents timHide As New Timer With {.Interval = 10}
    Dim isVerag360 As Boolean = False
    Dim creditsafe_newView As Boolean = False

    Sub New()

        ' Dieser Aufruf ist für den Designer erforderlich.
        InitializeComponent()

        Me.DoubleBuffered = True
        SetStyle(ControlStyles.OptimizedDoubleBuffer Or ControlStyles.UserPaint Or ControlStyles.AllPaintingInWmPaint Or ControlStyles.ResizeRedraw, True)
        UpdateStyles()
        ' Fügen Sie Initialisierungen nach dem InitializeComponent()-Aufruf hinzu.

    End Sub
    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 MyBase.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 Not IsDBNull(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_firmaFMZoll) AndAlso CInt(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_firmaFMZoll) = 19 Then isVerag360 = True

        If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige IsNot Nothing AndAlso VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige <> "" Then
            Dim where = If(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige.contains("A"), "", " AND Firma_ID IN (" & VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige & ") ")
            cboFirmaFMZOLL.fillWithSQL("SELECT cast([Firma_ID] as varchar(3)) as Firma_ID,[Firma_Bez]  FROM [tblFirma] WHERE 1=1 " & where, True, "FMZOLL", True)
        End If

        If FilialeNr > 0 Then
            UsrcntlKundeBearbeitenFull1.Filiale = FilialeNr
        End If

        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("KUNDEN_Bonität_Bearbeiten", "SDL") Then
            btnBonitaetBearbeiten.Visible = True
        End If

        Dim Paramslist As New cParameterList(VERAG_PROG_ALLGEMEIN.cAllgemein.PROGID)
        creditsafe_newView = Paramslist.GET_PARAMETER_VALUE_BOOL("Creditsafe_neueAnsicht")

        '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

                                                         initTABSDL_Allgemein()
                                                         changeTab(tabindex, AllgemeinToolStripMenuItem)
                                                         TabControl1_TabIndexChanged(tbcntrMain, New EventArgs)


                                                     Catch ex As Exception
                                                         VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                                                     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

        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OP_LADEN", "SDL") Then
            btnReloadOP.Visible = True
            btnOP.Visible = True
        End If

        If isVerag360 Then
            ToolStripMenuItem5.Visible = 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
                    picLogo.SizeMode = PictureBoxSizeMode.Zoom
                Else
                    picLogo.ImageLocation = Nothing
                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

            lblBonitaet.Text = If(KUNDE.Bonität, "")

        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 tbcntrUSTV.SelectedIndexChanged, tbcntrMDM.SelectedIndexChanged, tbcntrMain.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"

                            Dim ADR As New cAdressen(kdNr)
                            Dim isEU As Boolean = True
                            If Not IsDBNull(ADR.LandKz) Then
                                isEU = SQL.getValueTxtBySql("select MitgliedslandEU as bit from Währungstabelle where LandKz ='" & ADR.LandKz & "'", "FMZOLL")
                            End If
                            If Not isEU Then
                                scanEULizenz._TEXT_PDF = "Transportlizenz"
                                scanEULizenz.Name = scanEULizenz._TEXT_PDF
                                scanEULizenz.INIT(kdNr, "KUNDENDATEN")
                            Else
                                scanEULizenz._TEXT_PDF = "EU-Lizenz"
                                scanEULizenz.Name = scanEULizenz._TEXT_PDF
                                scanEULizenz.INIT(kdNr, "KUNDENDATEN")
                            End If

                            UsrCntlKundenlogin1.init(kdNr)

                            scanVertragVeragKd.INIT(kdNr, "KUNDENDATEN")
                            scanBankGarantie.INIT(kdNr, "KUNDENDATEN")
                            scanPersonalAusweisGF.INIT(kdNr, "KUNDENDATEN")
                            scanHRA.INIT(kdNr, "KUNDENDATEN")
                            scanHKA.INIT(kdNr, "KUNDENDATEN")

                            scanSonstiges.INIT(kdNr, "KUNDENDATEN")
                            scanUebernahmebestätigungen.INIT(kdNr, "KUNDENDATEN", "Übernahmebestätigungen")
                        Case "tbBesuchsberichte" : initTABBesuchsberichte()
                        Case "tbFremdrechnungen" : initTABFremdrechnungen()

                    End Select
                Case "tbUSTV"
                    Select Case tbcntrUSTV.SelectedTab.Name
                        Case "tbUSTVDokumente"
                            scanUSTVFABest.INIT(kdNr, "KUNDENDATEN", "FA_Bestaetigungen")
                            scanUSTVVollmachten.INIT(kdNr, "KUNDENDATEN", "USTV_Vollmachten")
                            scanUSTVsonstigeDokumente.INIT(kdNr, "KUNDENDATEN", "sonst_Dokumente")


                        Case "tbUSTVAntrage" : initTABUSTVAntraege()

                    End Select
                Case "tbZoll" : initTZOLL()
                Case "tbOfferte" : UsrCntlOfferte1.init(kdNr, isVerag360)
                Case "tbFIBU" : initFIBU()
                Case "tbRechnungen" : initBtns("Monat") : initRechnungen()

            End Select



        End If
        'tbcntrMDM.ResumeLayout()
    End Sub

    Sub initTABSDL_Allgemein()
        ' dgvSDLLeistungen.Columns.Clear()
        dgvOfferte.Columns.Clear()
        initDgvOfferte()
        showDgvOfferte()
        initDgvSperrliste()
        initDGVOffenePosten()
        initDGVUmsatz()
        initDGVUmsatzNachLeistungsNr()
        initStat()

        ' 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, isVerag360)

        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 initTABFremdrechnungen()
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("MDM_Fakturierung", Me) = 0 OrElse VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("MDM_LIEFERANTENRECHNUNGEN", "SDL") = 0 Then

            Dim usrcntlTMP As New usrcntlFremdrechnungen
            usrcntlTMP.Dock = DockStyle.Fill
            usrcntlTMP.kdNr = kdNr
            tbFremdrechnungen.Controls.Clear()
            tbFremdrechnungen.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


    Sub initTABUSTVAntraege()
        ' UsrCntlUSTV.kdNr_filter = True
        ' MsgBox("kdNr: " & kdNr)
        UsrCntlUSTV.init(kdNr)
    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

    Private Sub initFIBU()
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("BH_Hauptmenü", Me) = 0 Then

            If kdNr > 0 Then
                rtbGespreachsbericht.Text = checkNullStr(KUNDE.Gesprächsbericht)
                txtFIBUKuerzel.Text = checkNullStr(KUNDE_ERW.kde_BezFIBU)
                txtZinsbelastungNew.Text = checkNullStr(KUNDE_ERW.kde_zinssatz)
                txtZinsbelastungTolInTagen.Text = checkNullStr(KUNDE_ERW.kde_abwToleranzTage)

                initZNB()

            End If

        Else

            setInfo("info", "Sie sind für den Bereich FIBU 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],KundenSDL.Kundenlimit " &
                                   " 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

    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
            .Columns(12).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 & " and isnull(Verkauft,0) <> 1 and isnull(Abgemeldet,0) <> 1 ") & " aktive LKWs registriert" 'OK

        Dim dt = SQL.loadDgvBySql("SELECT Kunden.KundenNr as KundenNr, Kunden.UStV_SummeUmsatzsteuerbetragEUR, Kunden.UStV_SummeErstattungsbetragEUR, Kunden.UStV_Summe3470BetragEUR, Kunden.UStV_SummeVZBetragEUR, Kunden.UStV_SummeVorschaubetragEUR                                                               
                   FROM Kunden 
                   WHERE Kunden.KundenNr = " & kdNr, "FMZOLL")


        Dim GesamtUSteuer As Double = 0
        Dim GesamtErstattung As Double = 0
        Dim Differnezbetrag As Double = 0
        Dim Gesamt3470 As Double = 0
        Dim GesamtVZBetrag As Double = 0
        Dim VorschaubetrGes As Double = 0
        Dim OPSaldo As Double = 0
        Dim Risiko As Double = 0


        OPSaldo = CDbl((New SQL).getValueTxtBySql("SELECT isnull(sum(Gesamtausstand),0) FROM [Offene Posten] WHERE [Kontonummer]=" & kdNr, "FMZOLL"))

        If dt.Rows.Count = 1 Then
            GesamtUSteuer = dt.Rows(0).Item("UStV_SummeUmsatzsteuerbetragEUR")
            GesamtErstattung = dt.Rows(0).Item("UStV_SummeErstattungsbetragEUR")
            Gesamt3470 = dt.Rows(0).Item("UStV_Summe3470BetragEUR")
            GesamtVZBetrag = dt.Rows(0).Item("UStV_SummeVZBetragEUR")
            VorschaubetrGes = dt.Rows(0).Item("UStV_SummeVorschaubetragEUR")
        End If

        Differnezbetrag = GesamtUSteuer - GesamtErstattung

        Risiko = OPSaldo - Differnezbetrag - Gesamt3470 + GesamtVZBetrag - VorschaubetrGes

        txt3470Betrag.Text = Gesamt3470.ToString("C2")
        txtRisiko.Text = Risiko.ToString("C2")

        'lblStat_SdlLeistungen.Text = SQL.getSqlCount("SELECT Count(SDL.SDLNr) FROM SDL, Speditionsdienstleistungen WHERE KundenNr=" & kdNr & " and ISNULL(Archiviert,0) <> 1 and ISNULL(LKWAbgemeldet,0) <> 1 and ISNULL(Gesperrt,0) <> 1 and ISNULL(Defekt,0) <> 1 and ISNULL(Verloren,0) <> 1 and ISNULL(Gestohlen,0) <> 1 AND  SDL.SDLNr=Speditionsdienstleistungen.SDLNr ") & " aktive SDL Leistungen"

        With dgvLeistungen
            .DataSource = SQL.loadDgvBySql(" SELECT Count(SDL.SDLNr) as Anzahl , SDLBez as Leistung FROM SDL, Speditionsdienstleistungen 
                            WHERE KundenNr=" & kdNr & " and ISNULL(Archiviert,0) <> 1 and ISNULL(LKWAbgemeldet,0) <> 1 and ISNULL(Gesperrt,0) <> 1 and ISNULL(Defekt,0) <> 1 and ISNULL(Verloren,0) <> 1 and ISNULL(Gestohlen,0) <> 1 
                            AND  SDL.SDLNr=Speditionsdienstleistungen.SDLNr group by SDLBez order by Count(SDL.SDLNr) desc ")
            .Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .RowTemplate.Height = 20
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .RowTemplate.ReadOnly = True
            .RowHeadersVisible = False


        End With


        'Dim SQL_Diesel As String = " FROM SDL, Speditionsdienstleistungen WHERE KundenNr=" & kdNr & " AND ISNULL(Archiviert,0) <> 1 and ISNULL(LKWAbgemeldet,0) <> 1 and ISNULL(Gesperrt,0) <> 1 and ISNULL(Defekt,0) <> 1 and ISNULL(Verloren,0) <> 1 and ISNULL(Gestohlen,0) <> 1 AND SDL.SDLNr=Speditionsdienstleistungen.SDLNr AND SDL.SDLNr IN (100,101)"
        'Dim dt_Diesel As DataTable = SQL.loadDgvBySql("SELECT SDL.SDLNr,Count(SDL.SDLNr) as Anzahl" & SQL_Diesel & " Group by SDL.SDLNr", "SDL")
        'lblStat_SdlLeistungen_Diesel.Text = SQL.getSqlCount("SELECT Count(SDL.SDLNr)" & SQL_Diesel) & " aktive Tankkarten"

        ''If dt_Diesel.Rows.Count > 0 Then
        ''    lblStat_SdlLeistungen_Diesel.Text &= " ( "
        ''    For Each r In dt_Diesel.Rows
        ''        Dim Lieferant As String = ""
        ''        Select Case r.Item("SDLNr")
        ''            Case "100" : Lieferant = r.Item("Anzahl") & "x IDS "
        ''            Case "101" : Lieferant = r.Item("Anzahl") & "x RMC "
        ''        End Select

        ''        lblStat_SdlLeistungen_Diesel.Text &= Lieferant
        ''    Next
        ''    lblStat_SdlLeistungen_Diesel.Text &= ")"
        ''End If



        'Dim SQL_Maut As String = " FROM SDL, Speditionsdienstleistungen WHERE KundenNr=" & kdNr & " AND ISNULL(Archiviert,0) <> 1 and ISNULL(LKWAbgemeldet,0) <> 1 and ISNULL(Gesperrt,0) <> 1 and ISNULL(Defekt,0) <> 1 and ISNULL(Verloren,0) <> 1 and ISNULL(Gestohlen,0) <> 1 AND SDL.SDLNr=Speditionsdienstleistungen.SDLNr AND SDL.SDLNr BETWEEN 200 AND 218"
        'Dim dt_Maut As DataTable = SQL.loadDgvBySql("SELECT SDL.SDLNr,Count(SDL.SDLNr) as Anzahl" & SQL_Maut & " Group by SDL.SDLNr", "SDL")
        'lblStat_SdlLeistungen_Maut.Text = SQL.getSqlCount("SELECT Count(SDL.SDLNr)" & SQL_Maut) & " aktive Mautboxen/-karten"


        ''If dt_Maut.Rows.Count > 0 Then
        ''    lblStat_SdlLeistungen_Maut.Text &= " ( "
        ''    For Each r As DataRow In dt_Maut.Rows
        ''        Dim Lieferant As String = ""
        ''        Select Case r.Item("SDLNr")
        ''            Case "200" : Lieferant = r.Item("Anzahl") & "x AT "
        ''            Case "201" : Lieferant = r.Item("Anzahl") & "x DE "
        ''            Case "202" : Lieferant = r.Item("Anzahl") & "x TELEPASS "
        ''            Case "203" : Lieferant = r.Item("Anzahl") & "x CZ "
        ''            Case "205" : Lieferant = r.Item("Anzahl") & "x MotorWay "
        ''            Case "206" : Lieferant = r.Item("Anzahl") & "x DouBox "
        ''            Case "208" : Lieferant = r.Item("Anzahl") & "x MSE "
        ''            Case "209" : Lieferant = r.Item("Anzahl") & "x PL "
        ''            Case "210" : Lieferant = r.Item("Anzahl") & "x SI "
        ''            Case "211" : Lieferant = r.Item("Anzahl") & "x MSE-MP "
        ''            Case "212" : Lieferant = r.Item("Anzahl") & "x UTA "
        ''            Case "213" : Lieferant = r.Item("Anzahl") & "x HUGO "
        ''            Case "214" : Lieferant = r.Item("Anzahl") & "x PLOSE-RM "
        ''            Case "215" : Lieferant = r.Item("Anzahl") & "x PLOSE-IT "
        ''            Case "216" : Lieferant = r.Item("Anzahl") & "x PLOSE-CZ "
        ''            Case "217" : Lieferant = r.Item("Anzahl") & "x PLOSE-MP "
        ''            Case "218" : Lieferant = r.Item("Anzahl") & "x PLOSE-TM "

        ''        End Select

        ''        lblStat_SdlLeistungen_Maut.Text &= Lieferant
        ''    Next
        ''    lblStat_SdlLeistungen_Maut.Text &= ")"
        ''End If


    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)
                KUNDE_ERW = New VERAG_PROG_ALLGEMEIN.cKundenErweitert(kdNr)
                KUNDE_K_RE = New VERAG_PROG_ALLGEMEIN.cKundenKontakte(8, kdNr) 'Rechnungen an!
                KUNDE_K_GF = New VERAG_PROG_ALLGEMEIN.cKundenKontakte(13, kdNr) 'Rechnungen an!
                '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


                txtKundeninfo.ReadOnly = True

                txtKundeninfo.Text = ""


                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.Name_1) <> "", checkNullStr(ADRESSE.Name_1) & vbNewLine, ""))
                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.Name_2) <> "", checkNullStr(ADRESSE.Name_2) & vbNewLine, ""))
                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.Straße) <> "", checkNullStr(ADRESSE.Straße) & vbNewLine, ""))
                txtKundeninfo.AppendText(IIf(checkNullStr(KUNDE_ERW.kde_AdressZusatz) <> "", checkNullStr(KUNDE_ERW.kde_AdressZusatz) & vbNewLine, ""))
                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.LandKz) <> "", checkNullStr(ADRESSE.LandKz) & " - " & checkNullStr(ADRESSE.PLZ) & " - " & checkNullStr(ADRESSE.Ort) & vbNewLine, ""))
                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.PLZPF) <> "", checkNullStr(ADRESSE.PLZPF) & " - " & checkNullStr(ADRESSE.Postfach) & vbNewLine, ""))

                txtKundeninfo.AppendText(vbNewLine)

                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.Ansprechpartner) <> "", IIf(checkNullStr(ADRESSE.Anrede) <> "", ADRESSE.Anrede & " ", "") & ADRESSE.Ansprechpartner & vbNewLine, ""))

                txtKundeninfo.AppendText(vbNewLine)

                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.Telefon) <> "", "Tel.: " & ADRESSE.Telefon & vbNewLine, ""))
                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.Telefax) <> "", "Fax: " & ADRESSE.Telefax & vbNewLine, ""))
                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.Mobiltelefon) <> "", "Mobil: " & checkNullStr(ADRESSE.Mobiltelefon) & vbNewLine, ""))
                txtKundeninfo.AppendText(IIf(checkNullStr(ADRESSE.E_Mail) <> "", "E-Mail: " & ADRESSE.E_Mail & "; " & IIf(checkNullStr(ADRESSE.E_Mail2) <> "", " " & ADRESSE.E_Mail2 & ";", "") & vbNewLine, ""))

                lblKurzname.Text = checkNullStr(ADRESSE.Ordnungsbegriff)


                '----------- EV DEAKTIVIEREN------------------------
                lblFirmenname1.Text = checkNullStr(ADRESSE.Name_1)
                lblFirmenname2.Text = checkNullStr(ADRESSE.Name_2)
                lblStrasse.Text = checkNullStr(ADRESSE.Straße)
                lblAdressenzusatz.Text = checkNullStr(KUNDE_ERW.kde_AdressZusatz)
                lblLandPlzOrt.Text = checkNullStr(ADRESSE.LandKz) & " - " & checkNullStr(ADRESSE.PLZ) & " - " & checkNullStr(ADRESSE.Ort)
                lblPostfach.Text = checkNullStr(ADRESSE.PLZPF) & " - " & checkNullStr(ADRESSE.Postfach)
                lblAnsprechp.Text = ""
                lblAnsprechp.Text = IIf(checkNullStr(ADRESSE.Anrede) <> "", ADRESSE.Anrede & " ", "")
                lblAnsprechp.Text &= IIf(checkNullStr(ADRESSE.Ansprechpartner) <> "", ADRESSE.Ansprechpartner, "")

                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)


                Dim EmailRechnungen As String = "Rechnungen an: "
                txtEmailRE.Text = "-"
                txtEmailRE2.Text = ""
                If KUNDE_K_RE.hasEntry Then 'Rechnung an
                    EmailRechnungen &= KUNDE_K_RE.kkd_Email & "; "
                    EmailRechnungen &= KUNDE_K_RE.kkd_EmailCC & "; "
                Else
                    EmailRechnungen &= " - "
                End If

                txtKundeninfo.AppendText(vbNewLine)
                txtKundeninfo.AppendText(IIf(EmailRechnungen <> "", EmailRechnungen & vbNewLine, ""))

                Dim ansprechpartnerText As String = ""
                If KUNDE_K_GF.hasEntry Then
                    If lblAnsprechp.Text <> "" Then lblAnsprechp.Text &= " "

                    lblAnsprechp.Text &= "(GF:"
                    lblAnsprechp.Text &= IIf(checkNullStr(KUNDE_K_GF.kkd_AnsprechpartnerAnrede) <> "", KUNDE_K_GF.kkd_AnsprechpartnerAnrede & " ", "")
                    lblAnsprechp.Text &= IIf(checkNullStr(KUNDE_K_GF.kkd_AnsprechpartnerVorname) <> "", KUNDE_K_GF.kkd_AnsprechpartnerVorname & " ", "")
                    lblAnsprechp.Text &= IIf(checkNullStr(KUNDE_K_GF.kkd_AnsprechpartnerNachname) <> "", KUNDE_K_GF.kkd_AnsprechpartnerNachname.ToString.ToUpper, "")
                    lblAnsprechp.Text &= ")"

                    ansprechpartnerText = lblAnsprechp.Text
                    txtKundeninfo.AppendText(IIf(ansprechpartnerText <> "", ansprechpartnerText & vbNewLine, ""))
                End If

                lblUid.Text = ""
                Dim UID As String = ""
                If checkNullStr(ADRESSE.UstIdGeprüft) <> "" Then
                    lblUid.Text = "UID: " & checkNullStr(ADRESSE.UstIdKz) & checkNullStr(ADRESSE.UstIdNr)
                    UID = "UID: " & checkNullStr(ADRESSE.UstIdKz) & checkNullStr(ADRESSE.UstIdNr)
                    If checkNullStr(ADRESSE.UstIdGeprüft) <> "" Then
                        lblUid.Text &= " , geprüft am: " & checkNullStr(ADRESSE.UstIdGeprüft)
                        UID &= " , geprüft am: " & checkNullStr(ADRESSE.UstIdGeprüft)
                        txtKundeninfo.AppendText(UID & vbNewLine)
                    End If
                End If

                Dim SteuerNr As String = ""
                If checkNullStr(ADRESSE.Steuernummer) <> "" Then
                    If lblUid.Text <> "" Then lblUid.Text &= " / "
                    lblUid.Text &= "St-Nr.: " & checkNullStr(ADRESSE.Steuernummer)
                    SteuerNr = "Steuer-Nr.: " & checkNullStr(ADRESSE.Steuernummer)
                    txtKundeninfo.AppendText(SteuerNr & vbNewLine)
                End If

                If checkNullStr(KUNDE_ERW.kde_betreuer) <> "" Then
                    txtKundeninfo.AppendText(vbNewLine)
                    txtKundeninfo.AppendText("Betreuer: " & KUNDE_ERW.kde_betreuer & vbNewLine)
                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 KundenSDL.SDLNr in (select distinct(SDL.SDLNr) from SDL where SDL.SDLNr=KundenSDL.SDLNr AND SDL.KundenNr = KundenSDL.KundenNr) and SDLTypNr IN (1,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()

        Dim totalHeight As Integer = dgvSperrliste.ColumnHeadersHeight

        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

            totalHeight += r.Height

        Next

        dgvSperrliste.Height = totalHeight + 2


    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 dgvSperrliste.SelectionChanged, dgvOfferte.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"
        Else
            GroupBox5.Visible = True
            initStat()
            sender.text = "Statistik ausblenden"
        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
        btnBestelldateiErzeugen.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)

            If Not IsDBNull(dgvSDLLeistungenFull.SelectedRows(0).Cells("Kundenlimit").Value) Then
                txtKundenlimit.Text = dgvSDLLeistungenFull.SelectedRows(0).Cells("Kundenlimit").Value
            Else
                txtKundenlimit.Text = ""
            End If

            Select Case tmpSDLNr
                    Case 100 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.IDSKundenNr 'IDS
                    Case 200 : txtPartnerKdNr.Text = PartnerKdNrFromFMZOLL.ATKundenNr : btnBestelldateiErzeugen.Visible = True
                    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, 217, 218 : 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, 217, 218 : 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, 217, 218 : 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 MyBase.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
        Else
            picLogo.ImageLocation = Nothing
        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 MyBase.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
        cboFirmaFMZOLL.changeItem(VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA_ID)
        Button4.PerformClick()
    End Sub

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


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

        changeTab(5, sender)
    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 txtMautDEMasterPIN.KeyDown, txtMautDE_FlottenPIN.KeyDown, txtMautDE_BenutzerNr.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

    Private Sub ToolStripMenuItem8_Click_1(sender As Object, e As EventArgs) Handles ToolStripMenuItem8.Click
        changeTab(5, sender, 1)
    End Sub

    Private Sub btnOP_Click(sender As Object, e As EventArgs) Handles btnOP.Click
        If cboFirmaFMZOLL._value = "" Then
            MsgBox("Bitte Firma auswählen!")
        Else
            Dim KontoList As New List(Of String)
            KontoList.Add(KUNDE.KundenNrZentrale)
            frmBU_Mahnlauf.doZahlungserinnerung(Me.FindForm, "OP", KontoList, cboFirmaFMZOLL._value, "", {""})
        End If
    End Sub

    Private Sub btnReloadOP_Click(sender As Object, e As EventArgs) Handles btnReloadOP.Click
        Me.Cursor = Cursors.WaitCursor
        Try
            If KUNDE Is Nothing Then Exit Sub
            If cboFirmaFMZOLL._value <> "" Then
                If VERAG_PROG_ALLGEMEIN.cSyska_Interface.OP_Einlesen(cboFirmaFMZOLL._value, KUNDE.KundenNrZentrale) Then
                    MsgBox("Die OP-Liste wurde erfolgreich aktualisiert!")
                End If
            Else
                If VERAG_PROG_ALLGEMEIN.cSyska_Interface.OP_Einlesen_ALL(KUNDE.KundenNrZentrale) Then
                    MsgBox("Die OP-Liste wurde erfolgreich aktualisiert!")
                End If
            End If
            'initDGVUmsatz()
            initDGVOffenePosten()
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Sub initDGVOffenePosten()
        If KUNDE IsNot Nothing AndAlso KUNDE.FilialenNr IsNot Nothing Then
            If KUNDE.FilialenNr.ToString <> "" Then
                Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale(KUNDE.FilialenNr)
                    Case "IMEX" : initDGVOffenePostenIMEX()
                    Case Else : initDGVOffenePostenVERAG()
                End Select
            End If
        End If
    End Sub

    Sub initDGVOffenePostenIMEX()

        With dgvOffenePosten
            .Columns.Clear()
            If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige Is Nothing Then Exit Sub
            If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige = "" Then Exit Sub
            Dim where = ""



            .DataSource = SQL.loadDgvBySql("SELECT [KundenNr] as KdNr,[Datum] as Datum,[Rechnung] as Nummer,[Saldo] as Betrag,'-' as [OP-Saldo],'EUR' as Währung ,'-' as [KumSaldoEUR],[Buchungstext]   " &
                                                           " FROM [Offene_Posten_DVO] " &
                                                           " WHERE KundenNr='" & KUNDE.KundenNrZentrale & "' " & where & "  order BY datum DESC, [OP_ID]  DESC", "FMZOLL")
            If .Columns.Count > 0 Then

                .Columns("KdNr").Visible = False

                .Columns("Datum").Width = 70
                .Columns("Datum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

                .Columns("Betrag").Width = 75
                .Columns("Betrag").DefaultCellStyle.Format = "N2"
                .Columns("Betrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                '.Columns("OP-Saldo").Width = 75
                '.Columns("OP-Saldo").DefaultCellStyle.Format = "N2"
                '.Columns("OP-Saldo").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("OP-Saldo").Visible = False

                .Columns("Währung").Width = 60
                .Columns("Währung").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter


                '.Columns("KumSaldoEUR").Width = 80
                '.Columns("KumSaldoEUR").DefaultCellStyle.Format = "N2"
                '.Columns("KumSaldoEUR").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                .Columns("KumSaldoEUR").Visible = False

                .Columns("Buchungstext").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill


            End If

            Dim zahlungsziel = 10
            Dim sumZZ As Double = 0
            Dim sumNOTZZ As Double = 0
            Dim sumCredit As Double = 0
            Dim sumVK As Double
            If VERAG_PROG_ALLGEMEIN.cAllgemein.PARAMS.GET_PARAMETER_VALUE_BOOL("KUNDE_VK_OP") Then
                sumVK = getOffeneVK(KUNDE.KundenNrZentrale)

            End If

            Dim sumGes As Double = 0
            If IsNumeric(KUNDE.Zahlungsziel) Then zahlungsziel = KUNDE.Zahlungsziel



            Try
                For Each r As DataGridViewRow In .Rows
                    If DateDiff(DateInterval.Day, CDate(r.Cells("Datum").Value), Now) > zahlungsziel Then
                        If CDbl(r.Cells("Betrag").Value) > 0 Then sumZZ += CDbl(r.Cells("Betrag").Value)
                    Else
                        If CDbl(r.Cells("Betrag").Value) > 0 Then sumNOTZZ += CDbl(r.Cells("Betrag").Value)
                    End If
                    If CDbl(r.Cells("Betrag").Value) < 0 Then sumCredit += CDbl(r.Cells("Betrag").Value)


                    sumGes += CDbl(r.Cells("Betrag").Value)
                Next

            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try



        End With
        pnl.Visible = True


    End Sub



    Function getOffeneVK(KundenNrZentrale)
        Return SQL.getValueTxtBySql("SELECT isnull(sum([vk_Betrag]),0)FROM [tblVorauskassen] where vk_KdNr = '" & KundenNrZentrale & "' and vk_GeldEingetroffen=0 and vk_Datum > DATEADD(year,-1, GETDATE())
                                   and vk_storno=0 and (SELECT count(*) FROM Rechnungsausgang RG WHERE RG.FilialenNr = vk_FilialeNr and   RG.AbfertigungsNr= vk_AbfertigungsNr and vk_KdNr=rg.RechnungsKundenNr) =0", "FMZOLL")
    End Function
    Sub initDGVOffenePostenVERAG()


        With dgvOffenePosten
            If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige Is Nothing Then Exit Sub
            If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige = "" Then Exit Sub
            Dim where = ""
            Dim sort = "OP_ID DESC /*, Belegdatum DESC*/"
            If cboFirmaFMZOLL._value <> "" Then
                where = " AND Firma_ID=" & cboFirmaFMZOLL._value
                If cboFirmaFMZOLL._value = "19" Then
                    sort = "Belegdatum ASC"
                End If
            Else
                where = If(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige.contains("A"), "", " AND Firma_ID IN(" & VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige & ")")
            End If
            .DataSource = SQL.loadDgvBySql("SELECT [Kontonummer] as KdNr,[Belegdatum] as Datum,[Belegnummer] as Nummer,[Bruttobetrag] as Betrag,[Gesamtausstand] as [OP-Saldo],[Waehrung] as 'Währ.',[KumSaldoEUR],[Mahnstufe] as M, [Fälligkeitsdatum] as 'fällig am' ,[Buchungstext] as Referenz " &
                                                           " FROM [Offene Posten] " &
                                                           " WHERE [Kontonummer]='" & KUNDE.KundenNrZentrale & "' " & where & " ORDER BY " & sort, "FMZOLL")


            If .DataSource Is Nothing Then Exit Sub
            If .Columns.Count = 0 Then Exit Sub

            .Columns(0).Visible = False

            .Columns(1).Width = 70
            .Columns(1).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

            .Columns(2).Width = 80

            .Columns(3).Width = 75
            .Columns(3).DefaultCellStyle.Format = "N2"
            .Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

            .Columns(4).Width = 75
            .Columns(4).DefaultCellStyle.Format = "N2"
            .Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

            .Columns(5).Width = 40
            .Columns(5).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

            .Columns(6).Width = 80
            .Columns(6).DefaultCellStyle.Format = "N2"
            .Columns(6).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

            .Columns(7).Width = 20
            .Columns(6).DefaultCellStyle.Format = "N2"
            .Columns(7).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

            .Columns(8).Width = 70
            .Columns(8).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter


            .Columns(9).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            Dim OP_tmp As Double = 0

            If cboFirmaFMZOLL._value <> "" Then
                If .RowCount > 0 Then OP_tmp = If(.Rows(0).Cells("KumSaldoEUR").Value, 0)
            Else
                Dim where2 = If(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige.contains("A"), "", " AND Firma_ID IN(" & VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige & ")")
                Dim dt_OP As DataTable = SQL.loadDgvBySql("select isnull((select TOP 1 isnull(KumSaldoEUR,0) as abc FROM  [Offene Posten] WHERE [Kontonummer]='" & KUNDE.KundenNrZentrale & "' and [Offene Posten].Firma_ID=tblFirma.Firma_ID ORDER BY Belegdatum DESC),0) From tblFirma WHERE 1=1  " & where2, "FMZOLL")
                If dt_OP IsNot Nothing Then
                    For Each r In dt_OP.Rows
                        OP_tmp += r(0)
                    Next
                End If
            End If

            Dim sumVK As Double
            If VERAG_PROG_ALLGEMEIN.cAllgemein.PARAMS.GET_PARAMETER_VALUE_BOOL("KUNDE_VK_OP") Then
                sumVK = getOffeneVK(KUNDE.KundenNrZentrale)
                ' OP_tmp += sumVK
            End If

            Dim zahlungsziel = 10
            Dim sumZZ As Double = 0
            Dim sumNOTZZ As Double = 0

            Dim sumCredit As Double = 0
            If IsNumeric(KUNDE.Zahlungsziel) Then zahlungsziel = KUNDE.Zahlungsziel
            Try
                For Each r As DataGridViewRow In .Rows
                    If DateDiff(DateInterval.Day, CDate(r.Cells("Datum").Value), Now) > zahlungsziel Then
                        If CDbl(r.Cells("OP-Saldo").Value) > 0 Then sumZZ += CDbl(r.Cells("OP-Saldo").Value)
                    Else
                        If CDbl(r.Cells("OP-Saldo").Value) > 0 Then sumNOTZZ += CDbl(r.Cells("OP-Saldo").Value)
                    End If
                    If CDbl(r.Cells("OP-Saldo").Value) < 0 Then sumCredit += CDbl(r.Cells("OP-Saldo").Value)
                Next
            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

        End With
    End Sub

    Private Sub cboFirmaFMZOLL_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboFirmaFMZOLL.SelectedIndexChanged
        If loaded Then
            initDGVOffenePosten()
            initDGVUmsatz()
            initDGVUmsatzNachLeistungsNr()
        End If
    End Sub

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

    End Sub

    Sub initDGVUmsatz()
        With dgvUmsaetze
            If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige Is Nothing Then Exit Sub
            If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige = "" Then Exit Sub
            Dim where = ""
            If cboFirmaFMZOLL._value <> "" Then
                where = " AND Firma_ID=" & cboFirmaFMZOLL._value
            Else
                where = If(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige.contains("A"), "", " AND Firma_ID IN(" & VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige & ")")
            End If

            .DataSource = SQL.loadDgvBySql("SELECT [KundenNr],[Jahr],[steuerpflichtig],[steuerfrei],[Nettoumsatz],[MwSt],[Bruttoumsatz],[Währung],[Rechnungen],[Gutschriften],[Datum],[Nummer]" &
                                                           " FROM [tblKundenumsatz] " &
                                                           " WHERE [KundenNr]='" & kdNr & "' " & where & "  ORDER BY Jahr DESC", "FMZOLL")
            If .DataSource Is Nothing Then Exit Sub
            If .Columns.Count = 0 Then Exit Sub
            .Columns(0).Visible = False
            .Columns(11).Visible = False
            .Columns(1).Width = 45
            .Columns(1).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns(2).Width = 75
            .Columns(2).DefaultCellStyle.Format = "N2"
            .Columns(2).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .Columns(3).Width = 75
            .Columns(3).DefaultCellStyle.Format = "N2"
            .Columns(3).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .Columns(4).Width = 75
            .Columns(4).DefaultCellStyle.Format = "N2"
            .Columns(4).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .Columns(5).Width = 55
            .Columns(5).DefaultCellStyle.Format = "N2"
            .Columns(5).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .Columns(6).Width = 75
            .Columns(6).DefaultCellStyle.Format = "N2"
            .Columns(6).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
            .Columns(7).Width = 60
            .Columns(7).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns(8).Width = 55
            .Columns(8).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns(8).HeaderText = "Rechng."
            .Columns(9).Width = 53
            .Columns(9).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns(9).HeaderText = "Gutschr."
            .Columns(10).MinimumWidth = 65
            .Columns(10).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns(10).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

            If .RowCount > 0 Then
                '                txtUmsatzJahr.Text = String.Format("{0:n}", .Rows(0).Cells("Nettoumsatz").Value)
                'txtUmsatzJahr.Text = String.Format("{0:n}", .Rows(0).Cells("Nettoumsatz").Value)
                If IsNumeric(.Rows(0).Cells("Nettoumsatz").Value) Then
                    txtUmsatzJahr.Text = CDbl(.Rows(0).Cells("Nettoumsatz").Value).ToString("C")
                End If
                Label29.Text = "Umsatz " & .Rows(0).Cells("Jahr").Value & ":"
            Else
                txtUmsatzJahr.Text = ""
            End If
        End With

    End Sub


    Function dtUmsatzNachLeistungsNr() As DataTable

        Dim datatable As New DataTable

        If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige Is Nothing Then Return datatable
        If VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige = "" Then Return datatable
        Dim where = ""
        If cboFirmaFMZOLL._value <> "" Then
            where = " AND [RechnungsKundenNr] = " & kdNr & " AND Firma_ID=" & cboFirmaFMZOLL._value
        Else
            where = If(VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige.contains("A"), "", " AND Firma_ID IN(" & VERAG_PROG_ALLGEMEIN.cAllgemein.MITARBEITER.mit_FirmenDatenAnzeige & ")")
            where &= " AND [RechnungsKundenNr] = " & kdNr
        End If

        Dim sqlstr = ""
        sqlstr &= "  SELECT * FROM ( SELECT Leistungen.LeistungsNr, Leistungen.LeistungsBez,YEAR(Abfertigungsdatum ) [Year] , (RechnungsausgangPositionen.SteuerpflichtigerBetrag+RechnungsausgangPositionen.SteuerfreierBetrag  ) AS "
        sqlstr &= " [Der Wert] FROM Rechnungsausgang INNER JOIN (RechnungsausgangPositionen  LEFT JOIN Leistungen ON RechnungsausgangPositionen.LeistungsNr = Leistungen.LeistungsNr) ON (Rechnungsausgang.RK_ID = RechnungsausgangPositionen.RK_ID) "
        sqlstr &= " WHERE 1 = 1 "
        sqlstr &= where
        sqlstr &= " ) AS Rg"
        sqlstr &= " PIVOT( SUM([Der Wert]) FOR [Year] IN (" & getJahrString() & ")) AS MNamePivot"
        sqlstr &= " order by LeistungsNr"

        datatable = SQL.loadDgvBySql(sqlstr, "FMZOLL")

        Return datatable

    End Function

    Sub initDGVUmsatzNachLeistungsNr()
        With dgvUmsatzNachLeistngsNr

            .DataSource = dtUmsatzNachLeistungsNr()

            If .DataSource Is Nothing Then Exit Sub
            If .Columns.Count = 0 Then Exit Sub

            dgvUmsatzNachLeistngsNr.Columns(0).Frozen = True
            dgvUmsatzNachLeistngsNr.Columns(1).Frozen = True

            For i = 0 To dgvUmsatzNachLeistngsNr.ColumnCount - 1

                If i = 0 Then
                    .Columns(i).Width = 50
                End If

                If i > 1 Then
                    .Columns(i).Width = 75
                    .Columns(i).DefaultCellStyle.Format = "c2"
                    .Columns(i).DefaultCellStyle.FormatProvider = CultureInfo.GetCultureInfo("de-DE")
                    .Columns(i).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
                End If

            Next

        End With

    End Sub

    Function getJahrString() As String
        getJahrString = ""
        For j = Now.Year To 2010 Step -1
            getJahrString &= "[" & j & "],"
        Next
        getJahrString = getJahrString.Substring(0, getJahrString.Length - 1)
    End Function

    Private Sub btnBonitaetBearbeiten_Click(sender As Object, e As EventArgs) Handles btnBonitaetBearbeiten.Click

        Dim f1 As New frmBonitaet(kdNr)
        f1.ShowDialog(Me)
        KdSearchBox1.KdNr = kdNr  'aktualisieren

    End Sub

    Private Sub FlatButton6_Click(sender As Object, e As EventArgs) Handles FlatButton6.Click

        Dim f As New frmBonitätsverlauf(kdNr)
        f.newView = creditsafe_newView
        f.Show()
        AddHandler f.FormClosed, Sub()
                                     KdSearchBox1.KdNr = kdNr
                                 End Sub

    End Sub

    Private Sub PictureBox7_Click(sender As Object, e As EventArgs) Handles PictureBox7.Click
        If dgvUmsatzNachLeistngsNr.Rows.Count > 0 Then
            Me.Cursor = Cursors.WaitCursor

            Dim dt As DataTable = dtUmsatzNachLeistungsNr()

            If dt.Rows.Count > 0 Then
                cProgramFunctions.genExcelFromDT_NEW(dt, {"C1:C" & (dt.Rows.Count + 1), "D1:D" & (dt.Rows.Count + 1), "E1:E" & (dt.Rows.Count + 1), "F1:F" & (dt.Rows.Count + 1), "G1:G" & (dt.Rows.Count + 1), "H1:H" & (dt.Rows.Count + 1), "I1:I" & (dt.Rows.Count + 1), "J1:J" & (dt.Rows.Count + 1), "K1:K" & (dt.Rows.Count + 1)}, False)
            End If


            Me.Cursor = Cursors.Default
        End If


    End Sub

    Private Sub ToolStripMenuItem9_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem9.Click
        changeTab(4, sender)
    End Sub

    Private Sub ToolStripMenuItem10_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem10.Click
        changeTab(7, sender)
    End Sub

    Private Sub dgvRg_SelectionChanged(sender As Object, e As EventArgs) Handles dgvRg.SelectionChanged

    End Sub

    Private Sub btnRgPdf_Click(sender As Object, e As EventArgs) Handles btnRgPdf.Click, btnRgMail.Click
        Me.Cursor = Cursors.WaitCursor
        Dim PathList As New List(Of String)
        Try
            For Each RK_ID In getList_RK_ID()
                Dim RG_PATH = ""
                cFakturierung.doRechnungsDruck_SRorER(RK_ID,, False, 4, RG_PATH,,, True)

                PathList.Add(RG_PATH)
                If sender.Name = "btnRgPdf" Then Process.Start(RG_PATH)
            Next

            If sender.Name = "btnRgMail" Then


                Dim outl As New Outlook.Application
                Dim Mail As Microsoft.Office.Interop.Outlook.MailItem
                Mail = outl.CreateItem(0)

                Dim kundeMail As New cKunden()
                kundeMail = kundenSQL.getKundeByKdNr(kdNr)
                For Each pdf In PathList
                    Mail.Attachments.Add(pdf, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, , )
                Next

                Mail.To &= kundeMail.EMail
                Mail.CC &= kundeMail.EMail2
                Mail.Display()


            End If


        Catch ex As Exception
            MsgBox(ex.Message & ex.StackTrace)
        End Try
        Me.Cursor = Cursors.Default
    End Sub

    Function getList_RK_ID() As List(Of Integer)
        Dim listRgNr As New List(Of Integer)
        Dim list As New List(Of Integer)
        If dgvRg.SelectedRows.Count > 0 Then
            For Each r As DataGridViewRow In dgvRg.SelectedRows
                If listRgNr.FindIndex((Function(x) x.ToString = r.Cells("RechnungsNr").Value)) < 0 Then
                    list.Add(r.Cells("RK_ID").Value)
                    listRgNr.Add(r.Cells("RechnungsNr").Value)
                End If
            Next
        End If
        Return list
    End Function

    Sub initBtns(MonatJahr)
        Try
            'MsgBox(RG_MONAT.ToString("MMMM yy"))
            btnMonat.Text = RG_MONAT.ToString("MMMM yy")
            Select Case MonatJahr
                Case "Monat"
                Case "Jahr", "Tag"
            End Select
            initRechnungen()
        Catch ex As Exception

        End Try

    End Sub

    Sub initRechnungen()
        With dgvRg
            Dim sqlStr = ""
            sqlStr &= "  SELECT TOP 1000 [Rechnungsart],RK_ID,[RechnungsNr],[RechnungsDatum],case when [DruckDatumZeit] is null then 0 else 1 end as gedruckt, "
            sqlStr &= " ( SELECT SUM(isnull([SteuerpflichtigerBetrag],0)+isnull([SteuerfreierBetrag],0))  FROM [RechnungsausgangPositionen] where [RechnungsausgangPositionen].RK_ID=[Rechnungsausgang].RK_ID ) as Rechnungsbetrag,"
            sqlStr &= " Sammelrechnung, [FilialenNr],[AbfertigungsNr],[UnterNr],[Abfertigungsdatum],  isnull(cast(RechnungsKundenNr as nvarchar(7)) + ' ','') + [RechnungsName 1] as [RechnungAn], "
            sqlStr &= " isnull(cast([VermittlerKundenNr] as nvarchar(7)) + ' ','') + [VermittlerName 1] as Vermittler, [LKW Kennzeichen],Sachbearbeiter "
            sqlStr &= " FROM [Rechnungsausgang] WHERE RechnungsKundenNr=@KundenNr AND RechnungsDatum BETWEEN @RechnungsDatum_Von AND @RechnungsDatum_Bis "

            Dim SQL_PARAM As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
            SQL_PARAM.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("KundenNr", kdNr))
            SQL_PARAM.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("RechnungsDatum_Von", RG_MONAT))
            SQL_PARAM.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("RechnungsDatum_Bis", RG_MONAT.AddMonths(1).AddDays(-1)))
            .SET_SQL(sqlStr & " ORDER BY RechnungsDatum DESC", "FMZOLL", SQL_PARAM)
            .LOAD()

            '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

            .Columns("RK_ID").Visible = False

            .Columns("RechnungsNr").Width = 70
            .Columns("RechnungsNr").HeaderText = "Rechnugs-Nr"
            .Columns("RechnungsNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("RechnungsNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("RechnungsDatum").Width = 100
            .Columns("RechnungsDatum").HeaderText = "Rg-Dat."
            .Columns("RechnungsDatum").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("RechnungsDatum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("Sammelrechnung").Width = 45
            .Columns("Sammelrechnung").HeaderText = "SR"

            .Columns("Rechnungsart").Width = 45
            .Columns("Rechnungsart").HeaderText = "Beleg"

            .Columns("Rechnungsbetrag").Width = 100
            .Columns("Rechnungsbetrag").HeaderText = "Rechnungsbetrag"
            .Columns("Rechnungsbetrag").DefaultCellStyle.Format = "C"
            .Columns("Rechnungsbetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight

            .Columns("FilialenNr").Width = 45
            .Columns("FilialenNr").HeaderText = "Filiale"
            .Columns("FilialenNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("FilialenNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("AbfertigungsNr").Width = 70
            .Columns("AbfertigungsNr").HeaderText = "Abf-Nr"
            .Columns("AbfertigungsNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("AbfertigungsNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("UnterNr").Width = 45
            .Columns("UnterNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("UnterNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("Abfertigungsdatum").Width = 100
            .Columns("Abfertigungsdatum").HeaderText = "Abf-Dat."
            .Columns("Abfertigungsdatum").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("Abfertigungsdatum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("RechnungAn").MinimumWidth = 150
            .Columns("RechnungAn").HeaderText = "Rechnung an"
            .Columns("RechnungAn").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            '.Columns("Absender").MinimumWidth = 150
            '.Columns("Absender").HeaderText = "Absender"
            '.Columns("Absender").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns("Vermittler").MinimumWidth = 150
            .Columns("Vermittler").HeaderText = "Auftraggeber"
            .Columns("Vermittler").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            '.Columns("Empfänger").MinimumWidth = 150
            '.Columns("Empfänger").HeaderText = "Empfänger"
            '.Columns("Empfänger").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns("LKW Kennzeichen").Width = 120
            .Columns("LKW Kennzeichen").HeaderText = "LKW Kennzeichen"

            .Columns("Sachbearbeiter").MinimumWidth = 100
            .Columns("Sachbearbeiter").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

        End With
    End Sub

    Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
        RG_MONAT = RG_MONAT.AddMonths(1)
        initBtns("Monat")
    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        RG_MONAT = RG_MONAT.AddMonths(-1)
        initBtns("Monat")
    End Sub

    Private Sub dgvRg_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvRg.CellContentDoubleClick

        If dgvRg.SelectedRows.Count = 0 Then Exit Sub

        Dim f As New frmKundenUebersichtZollRgDetails(dgvRg.SelectedRows(0).Cells("RK_ID").Value, dgvRg.SelectedRows(0).Cells("gedruckt").Value)
        f.ShowDialog()

        dgvRg.RELOAD()

    End Sub

    Sub initZNB()

        With dgvZinsnachberechnung
            Dim sqlStr = ""
            sqlStr &= "  SELECT TOP 1000 [belegNr] ,[belegDatum],[buchungstext],[zinsbetrag],[zinssatz],[ueberschreitungInTagen],[belegZahlungsziel],[timestamp], cast(case when [verrechnet] is null then 0 else 1 end as bit) as verrechnet, rk_id"
            sqlStr &= " FROM [tblMDM_Zinsberechnung] WHERE kundenNr=" & kdNr

            .SET_SQL(sqlStr & " ORDER BY belegdatum desc", "FMZOLL")
            .LOAD()

            '.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells


            .Columns("belegNr").Width = 70
            .Columns("belegNr").HeaderText = "Beleg-Nr"
            .Columns("belegNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("belegNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("belegDatum").Width = 100
            .Columns("belegDatum").HeaderText = "Beleg-Dat."
            .Columns("belegDatum").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("belegDatum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            '.Columns("Rechnungsbetrag").Width = 100
            '.Columns("Rechnungsbetrag").HeaderText = "Belegbetrag"
            '.Columns("Rechnungsbetrag").DefaultCellStyle.Format = "C"
            '.Columns("Rechnungsbetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight

            .Columns("buchungstext").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("buchungstext").HeaderText = "Text"
            .Columns("buchungstext").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight


            .Columns("zinsbetrag").Width = 100
            .Columns("zinsbetrag").HeaderText = "Zinsbetrag"
            .Columns("zinsbetrag").DefaultCellStyle.Format = "C"
            .Columns("zinsbetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight

            .Columns("zinssatz").Width = 100
            .Columns("zinssatz").HeaderText = "Zinssatz"
            .Columns("zinssatz").DefaultCellStyle.Format = "C"
            .Columns("zinssatz").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight


            .Columns("ueberschreitungInTagen").Width = 45
            .Columns("ueberschreitungInTagen").HeaderText = "Tage"
            .Columns("ueberschreitungInTagen").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("ueberschreitungInTagen").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter


            .Columns("belegZahlungsziel").Width = 45
            .Columns("belegZahlungsziel").HeaderText = "ZZ"
            .Columns("belegZahlungsziel").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("belegZahlungsziel").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("verrechnet").Width = 50
            .Columns("verrechnet").HeaderText = "Fakt."
            .Columns("verrechnet").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("verrechnet").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("timestamp").Width = 100
            .Columns("timestamp").HeaderText = "Erstellt am"
            .Columns("timestamp").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("timestamp").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            .Columns("RK_ID").Visible = False


            Dim sumOffeneZB As Double = 0
            Dim sumVerrZB As Double = 0


            For Each r As DataGridViewRow In .Rows
                If (IsNumeric(r.Cells("zinsbetrag").Value)) Then
                    If Not IsDBNull(r.Cells("verrechnet").Value) AndAlso r.Cells("verrechnet").Value > 0 Then
                        sumVerrZB += If(IsNumeric(r.Cells("zinsbetrag").Value), CDbl(r.Cells("zinsbetrag").Value), 0)
                    Else
                        sumOffeneZB += If(IsNumeric(r.Cells("zinsbetrag").Value), CDbl(r.Cells("zinsbetrag").Value), 0)
                    End If
                End If




            Next

            lblZNB_offen.Text = sumOffeneZB
            lblZNB_verrechnet.Text = sumVerrZB


        End With





    End Sub


    Private Sub btnBestelldateiErzeugen_Click(sender As Object, e As EventArgs) Handles btnBestelldateiErzeugen.Click

        If Not cm_goboxen.Items.ContainsKey("create") Then
            Dim create = New ToolStripMenuItem() With {.Text = "Anlage", .Name = "create", .Font = New Font(Me.Font.FontFamily, Me.Font.Size)}
            cm_goboxen.Items.Add(create)
            AddHandler create.Click, AddressOf mnuItem_Clicked
        End If


        If Not cm_goboxen.Items.ContainsKey("show") Then
            Dim show = New ToolStripMenuItem() With {.Text = "Ansicht", .Name = "show", .Font = New Font(Me.Font.FontFamily, Me.Font.Size)}
            AddHandler show.Click, AddressOf mnuItem_Clicked
            cm_goboxen.Items.Add(show)
        End If

        If Not cm_goboxen.Items.ContainsKey("send") Then
            Dim send = New ToolStripMenuItem() With {.Text = "Senden", .Name = "send", .Font = New Font(Me.Font.FontFamily, Me.Font.Size)}
            AddHandler send.Click, AddressOf mnuItem_Clicked
            cm_goboxen.Items.Add(send)
        End If

        cm_goboxen.Show(Cursor.Position)


    End Sub

    Private Sub mnuItem_Clicked(sender As Object, e As EventArgs)
        cm_goboxen.Hide()
        Dim item As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)

        If item IsNot Nothing Then
            If item.Name = "create" Then
                Dim f As New frmGoMautBoxen_Bestellung(KUNDE, ADRESSE, KUNDE_ERW)
                f.ShowDialog()
            ElseIf item.Name = "show" Then
                GoBoxBestelldaten_show()
            ElseIf item.Name = "send" Then
                GOBoxBestellung_erzeugen()
            Else
                MsgBox("Funktion nicht implementiert!")
            End If

        End If

    End Sub

    Private Sub GoBoxBestelldaten_show()

        Try

            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim frm As New Form
            Dim dgv As New DataGridView()
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT gb_adressNr as Adresse, gb_CardNum as KartenNr, gb_CardValidMonth as [gültig bis_Monat] , gb_CardValidYear  as [gültig bis_Jahr] , gb_licensePlate as Kennzeichen, gb_licensePlateNat as Land, gb_Axles as Achsen FROM [tblGOBOXBestellungen] WHERE gb_bestelldatum Is Null AND gb_bestellNr Is Null
                                                    ", "FMZOLL")


            If dt.Rows.Count = 0 Then MsgBox("Keine nicht abgeschickten Bestellungen vorhanden!") : Exit Sub

            dgv.DataSource = dt


            If dgv IsNot Nothing Then
                frm.Size = New Size(500, 500)
                dgv.Size = New Size(frm.Size.Width - 50, frm.Size.Height - 50)
                dgv.Dock = DockStyle.Fill
                dgv.Anchor = AnchorStyles.Left
                dgv.Anchor = AnchorStyles.Top
                dgv.ReadOnly = True
                frm.Controls.Add(dgv)
                frm.StartPosition = FormStartPosition.CenterScreen
                frm.ShowDialog()
            End If


        Catch ex As System.Exception

            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Sub

    Private Sub GOBoxBestellung_erzeugen()

        Dim dateBestelldatum As Date = Date.Now
        Dim intBestellnummer As Integer
        Dim lngBestellanzahl As Long
        Dim strDateiname As String

        Try
            ' Kreditkarten prüfen/eintragen

            Dim dt_offeneBestellungen As New DataTable
            dt_offeneBestellungen = SQL.loadDgvBySql("SELECT gb_bestelldatum, gb_bestellNr, gb_adressNr, gb_CardNum, gb_CardValidMonth, gb_CardValidYear, gb_licensePlate, gb_licensePlateNat, gb_Axles FROM [tblGOBOXBestellungen] WHERE gb_bestelldatum Is Null  AND gb_bestellNr Is Null", "FMZOLL")

            If dt_offeneBestellungen IsNot Nothing Then

                lngBestellanzahl = dt_offeneBestellungen.Rows.Count

                For Each r As DataRow In dt_offeneBestellungen.Rows

                    If Not IsDBNull(r.Item("gb_adressNr")) AndAlso Not IsDBNull(r.Item("gb_CardNum")) AndAlso Not IsDBNull(r.Item("gb_CardValidMonth")) AndAlso Not IsDBNull(r.Item("gb_CardValidYear")) Then

                        Dim countKK = SQL.getValueTxtBySql("SELECT COUNT(*) FROM Kreditkarten WHERE AdressenNr = " & r.Item("gb_adressNr") & " AND KartenNr =" & r.Item("gb_CardNum"), "FMZOLL")

                        If countKK = "0" Then

                            If SQL.doSQL("INSERT INTO Kreditkarten (AdressenNr, KartenNr, Kartenfreischaltungsdatum, Kartenablaufmonat, Kartenablaufjahr, Kartensperre, Zeitstempel, Sachbearbeiter)
                            VALUES ('" & r.Item("gb_adressNr") & "','" & r.Item("gb_CardNum") & "','" & Date.Now & "','" & r.Item("gb_CardValidMonth") & "','" & r.Item("gb_CardValidYear") & "','0','" & Now() & "','" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME & "')", "FMZOLL") Then


                            End If


                        End If


                    End If

                Next



            End If

            ' 4️ Bestelldaten lesen
            Dim dtBestellungen As DataTable = SQL.loadDgvBySql("SELECT gb_ID,gb_bestelldatum, gb_bestellNr, gb_adressNr, gb_CardNum, gb_CardValidMonth, gb_CardValidYear, gb_licensePlate, gb_licensePlateNat, gb_Axles FROM [tblGOBOXBestellungen] WHERE gb_bestelldatum Is Null  AND gb_bestellNr Is Null", "FMZOLL")
            If dtBestellungen.Rows.Count = 0 Then
                MessageBox.Show("Keine Bestelldaten vorhanden.", "Bestelldatei erzeugen", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            '5 Neue Bestellnummer bestimmen
            Dim bestellNr As String = SQL.getValueTxtBySql("SELECT Top(1) gb_bestellNr FROM [tblGOBOXBestellnummern] ORDER BY gb_bestelldatum DESC", "FMZOLL")
            If bestellNr <> "" AndAlso IsNumeric(bestellNr) Then
                intBestellnummer = CInt(bestellNr)

                If intBestellnummer = 9999 Then
                    intBestellnummer = 1
                Else
                    intBestellnummer = intBestellnummer + 1
                End If

            Else
                intBestellnummer = 1

            End If


            ' 6️ Datensätze aktualisieren
            Dim ID_bestellungen As String = ""
            If dtBestellungen.Columns.Contains("gb_ID") Then
                Dim dtNew As DataTable = dtBestellungen.Rows.Cast(Of DataRow)().Where(Function(row) Not row.ItemArray.All(Function(field) field Is DBNull.Value Or field.Equals(""))).CopyToDataTable()
                If dtNew.Rows.Count > 0 Then
                    Dim counter = 0
                    For Each r As DataRow In dtNew.Rows
                        ID_bestellungen &= r.Item(0)
                        counter = counter + 1
                        If (dtNew.Rows.Count <> 0 And counter <> dtNew.Rows.Count) Then
                            ID_bestellungen &= ","
                        End If
                    Next
                End If
            End If
            If ID_bestellungen <> "" Then
                SQL.doSQL("UPDATE tblGOBOXBestellungen  SET gb_bestelldatum = '" & dateBestelldatum.ToShortDateString & "', gb_bestellNr = " & intBestellnummer & " WHERE gb_ID in (" & ID_bestellungen & ")", "FMZOLL")
            End If

            ' 7 Bestellnummer speichern
            If IsDate(dateBestelldatum) AndAlso IsNumeric(intBestellnummer) AndAlso IsNumeric(lngBestellanzahl) Then

                SQL.doSQL("INSERT INTO tblGOBOXBestellnummern (gb_bestelldatum, gb_bestellNr, gb_bestellAnzahl) VALUES ('" & dateBestelldatum.ToShortDateString & "', " & intBestellnummer & ", " & lngBestellanzahl & ")", "FMZOLL")

            End If



            For Each row In dtBestellungen.Rows


                If row("gb_adressNr") Is Nothing OrElse Not IsNumeric(row("gb_adressNr")) Then Continue For
                If row("gb_licensePlate") Is Nothing OrElse row("gb_licensePlate") = "" Then Continue For

                ' KundenSDL Verwaltung.
                Dim KundenNr As String = SQL.getValueTxtBySql("SELECT KundenNr FROM KundenSDL WHERE KundenNr = " & row("gb_adressNr"), "SDL")

                If KundenNr = "" Then

                    Dim Kunde As New cKundenSDL(row("gb_adressNr"), 200)
                    Kunde.Erfassungsdatum = Now
                    Kunde.Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME
                    Kunde.SAVE()


                End If

                ' LKW Verwaltung.
                Dim LKWNr As String = SQL.getValueTxtBySql("Select KfzKennzeichen FROM dbo.SDL WHERE KundenNr = " & row("gb_adressNr") & " AND KfzKennzeichen = '" & row("gb_licensePlate") & "'", "SDL")

                If LKWNr = "" Then

                    Dim LKW As New cSDL_LKW(row("gb_adressNr"), row("gb_licensePlate"))
                    LKW.Erfassungsdatum = Now
                    LKW.Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME
                    LKW.Nationalität = row("gb_licensePlateNat")
                    LKW.SAVE()


                End If

                ' SDL Verwaltung.

                Dim SDLVerw As String = SQL.getValueTxtBySql("Select KundenNr FROM dbo.SDL WHERE KundenNr = " & row("gb_adressNr") & " AND KfzKennzeichen = '" & row("gb_licensePlate") & "' AND SDLNr = 200", "SDL")

                If SDLVerw = "" Then

                    Dim lfdNr As Integer = CInt(SQL.getValueTxtBySql("SELECT isnull(Max(History),1)  As Historywert, COUNT(*) AS Anzahl FROM SDL WHERE (KundenNr = " & row("gb_adressNr") & ") AND (SDLNr = 200)", "SDL"))

                    Dim SDL_DS As New cSDL(row("gb_adressNr"), row("gb_licensePlate"), 200)

                    SDL_DS.Sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME
                    SDL_DS.BestellNr = row("gb_bestellNr")
                    SDL_DS.Bestelldatum = row("gb_bestelldatum")
                    SDL_DS.Kategorie = row("gb_Axles")
                    SDL_DS.KartenNr = row("gb_CardNum")
                    SDL_DS.Erfassungsdatum = Now()
                    SDL_DS.History = lfdNr

                    If SDL_DS.SAVE() Then

                        SQL.doSQL("INSERT INTO SDLLog (KundenNr, KfzKennzeichen, SDLNr,History, BestellNr, Bestelldatum, KartenNr, Kategorie, Erfassungsdatum, Sachbearbeiter, RIUD, Name, Zeitstempel ) VALUES 
                                (" & row("gb_adressNr") & ",'" & row("gb_licensePlate") & "',200, " & lfdNr & "," & intBestellnummer & ", '" & dateBestelldatum.ToShortDateString & "'," & row("gb_CardNum") & "," & row("gb_Axles") & ", '" & Now() & "','" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME & "','I','" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME & "','" & Now() & "')", "SDL")

                    End If

                End If

            Next

            'CSV erzeugen:
            Dim SQL_String As String = "Select Top(1) 'S' As [Transaction Type], ''As Company1, ' ' As Company2, ' ' As CompanyStreet, ' ' As CompanyNumber, ' ' As CompanyCode, ' ' As CompanyCity, ' ' As CompanyCountry, ' ' As CompanyCountryAbbr, ' ' As CompanyTelephone, ' ' As CompanyTelefax, ' ' As Salutation, ' ' As Title, ' ' As FirstName, ' ' As LastName, ' ' As Email, ' ' As PersonLanguage, ' ' As [License plate], ' ' As [License plate Nationality], ' ' As VehicleType, ' ' As Axles, ' ' As [Stammnummer For Tripon Orders only], ' ' As CardNum, ' ' As CardValidMonth, ' ' As CardValidYear FROM [tblGOBOXBestellungen]
                        UNION ALL 
            Select gb_transactionTyp, gb_company1, gb_company2, gb_companyStreet, gb_companyStreetNr, gb_companyPostalcode, gb_companyCity, gb_companyCountry, gb_companyCountryISO, gb_companyTel, gb_companyFax, gb_salutation, gb_title, gb_firstname, gb_lastname, gb_email, gb_personLanguage, gb_licensePlate, gb_licensePlateNat, gb_vehicleTyp, gb_Axles, '', gb_CardNum,RIGHT('00' + CAST(gb_CardValidMonth AS VARCHAR(2)), 2) , RIGHT('00' + CAST(gb_CardValidYear AS VARCHAR(2)), 2) 
            From [tblGOBOXBestellungen] where gb_bestellNr = " & intBestellnummer & " and gb_transactionTyp = 'N'
            UNION SELECT TOP (1) 'E', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' FROM [tblGOBOXBestellungen]"

            Dim dt_export As DataTable = SQL.loadDgvBySql(SQL_String, "FMZOLL")

            Dim outl As New Outlook.Application
            Dim Mail As Microsoft.Office.Interop.Outlook.MailItem
            Mail = outl.CreateItem(0)

            Mail.Subject = "GO-BOX Bestellung Nr. " & intBestellnummer & " vom " & dateBestelldatum.ToShortDateString

            strDateiname = "PO_VG_" & Format(intBestellnummer, "0000") & "_" & Format(dateBestelldatum, "ddmmyy") & ".csv"

            Dim Path As String = VERAG_PROG_ALLGEMEIN.cProgramFunctions.genCSVFromDT(dt_export,,, strDateiname)

            'muss genauer Bezeichnung haben!!
            '"PO_VG_" & Format(Forms!frm_GO_BOX_Bestellvorgang!Bestellnummer, "0000") & "_" & Format(Forms!frm_GO_BOX_Bestellvorgang!Bestelldatum, "ddmmyy") & ".csv"


            Mail.Body = "Als Anhang senden wir Ihnen die Datei """ & strDateiname & """ mit den GO-BOX-Bestellungen." &
                     vbCrLf & vbCrLf & "Mit freundlichen Grüssen" &
                     vbCrLf & "VERAG Spedition AG" &
                     vbCrLf & "ASFINAG-Mautabteilung" &
                     vbCrLf & "______________________" &
                     vbCrLf & "Tel. +43 7711 2777 - 14 o. 17 o. 47" &
                     vbCrLf & "Fax +43 7711 3386" &
                     vbCrLf & "email: maut.asfinag@verag.ag" &
                     vbCrLf & "www.verag.ag"


            Mail.Attachments.Add(Path, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue,, strDateiname)

            Mail.Display()
            Me.Cursor = Cursors.Default


        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try

    End Sub

    Private Sub btn_FIBU_speichern_Click(sender As Object, e As EventArgs) Handles btn_FIBU_speichern.Click
        KUNDE_ERW.kde_BezFIBU = checkNullStr(txtFIBUKuerzel.Text)
        KUNDE_ERW.kde_abwToleranzTage = checkNullStr(txtZinsbelastungTolInTagen.Text)

        If Not String.IsNullOrWhiteSpace(txtZinsbelastungNew.Text) Then
            Dim zinssatzText As String = txtZinsbelastungNew.Text.Replace(",", ".")
            Dim zinssatzValue As Decimal

            If Decimal.TryParse(zinssatzText, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, zinssatzValue) Then
                If zinssatzValue <= 999.99D AndAlso zinssatzValue >= -999.99D Then
                    KUNDE_ERW.kde_zinssatz = zinssatzValue
                End If

            End If
        Else
            KUNDE_ERW.kde_zinssatz = Nothing
        End If

        KUNDE_ERW.SAVE()

        If Not (KUNDE.Gesprächsbericht <> "" AndAlso checkNullStr(rtbGespreachsbericht.Text) = "") Then
            If KUNDE.Gesprächsbericht = "" AndAlso checkNullStr(rtbGespreachsbericht.Text) <> "" Or KUNDE.Gesprächsbericht <> checkNullStr(rtbGespreachsbericht.Text) Then
                KUNDE.Gesprächsbericht = checkNullStr(rtbGespreachsbericht.Text)
                KUNDE.SAVE()
            End If
        Else
            MsgBox("Feld Gesprächsbericht darf nicht leer sein")
        End If

    End Sub

    Private Sub dgvZinsnachberechnung_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvZinsnachberechnung.CellDoubleClick

        If dgvZinsnachberechnung.SelectedRows.Count = 0 Then Exit Sub

        If Not IsDBNull(dgvZinsnachberechnung.SelectedRows(0).Cells("RK_ID").Value) AndAlso IsNumeric(dgvZinsnachberechnung.SelectedRows(0).Cells("RK_ID").Value) Then

            Dim f As New SDL.frmAbrechnungsMaskeEinzeln(dgvZinsnachberechnung.SelectedRows(0).Cells("RK_ID").Value)
            f.Show(Me)


        End If

    End Sub

    Private Sub btnRgMail_Click(sender As Object, e As EventArgs) Handles btnRgMail.Click

    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click

        Dim rptKundeUebersicht As New SDL.rptKundeUebersicht(kdNr, 19)
        Dim rpt As New frmPrintLayout
        rpt.Text = ""

        rpt.Viewer.LoadDocument(rptKundeUebersicht)

        rpt.Viewer.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
        rpt.Show()
    End Sub

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

    End Sub
End Class

