Imports System.Data.SqlClient
Imports System.Globalization
Imports System.IO
Imports SDL.EORI
Imports sun.invoke.empty

Public Class usrCntlKundenuebersicht
    'Implements INotifyPropertyChanged
    Public superuser As Boolean = False
    Dim KUNDE As VERAG_PROG_ALLGEMEIN.cKunde = Nothing
    Public KUNDE_ERW As VERAG_PROG_ALLGEMEIN.cKundenErweitert = Nothing
    Public ADRESSE As VERAG_PROG_ALLGEMEIN.cAdressen = Nothing
    Public AUFSCHUB As List(Of VERAG_PROG_ALLGEMEIN.cKundenAufschubkonten) = Nothing

    Dim VERAGSQL As New VERAG_PROG_ALLGEMEIN.SQL

    Public kdNr As Integer = -1
    Private dataAdapterFirma As New SqlDataAdapter
    ' Private dataFirma As New DataTable
    Private bindingFirma As New BindingSource
    Dim FISKAL As cFiskal_Daten = Nothing

    Private abfertigungsverbotText As String = ""
    Private gespraechsberichtText As String = ""
    Private korrAdresseText As String = ""
    Private firmenwortlautFiskal As String = ""
    Dim trennungBesonderheiten = False

    Dim f_bold = New Font(Me.Font.FontFamily, 8, FontStyle.Bold)
    Dim f_norm = New Font(Me.Font.FontFamily, 8, FontStyle.Regular)

    Dim WithEvents timerOP As New Timer

    Private loaded As Boolean = False
    Dim RG_MONAT As Date = CDate("01." & Now.Month & "." & Now.Year) '.AddMonths(-1)

    ' Dim cDATENSERVER As New VERAG_PROG_ALLGEMEIN.cDATENSERVER
    Dim cFormularManager As New VERAG_PROG_ALLGEMEIN.cFormularManager
    '  Dim BERECHTIGUNEN As List(Of cBerechtigungen)
    Dim WithEvents timer_EORI As New Timer()
    Dim f_EORI As Form
    Dim f_EORI_PDF As String = ""

    Dim SQL As New SQL
    Dim cSqlDb As New cSqlDb
    Dim FUNC As New cProgramFunctions
    '  Public USRID As Integer = -1
    ' Public userfullname As String = ""
    'Public username As String = ""
    Dim db As New DataSet
    Dim WHEREStatistik = ""
    Public selectedTAB = ""
    Property BER_STUFE = 99

    Public Sub New()
        Try
            ' initialize added component on form1, which is menu strip;
            'note: if you have added any second component alongside menu
            'strip, such as context menu strip just add additional code 
            'line under InitializeComponent(), and it will work;
            InitializeComponent()
            '    MenuStripSDL.Renderer = New MyRenderer()
        Catch ex As Exception

        End Try
    End Sub


    Public Sub New(KdNr As Integer)
        Try
            InitializeComponent()
            Me.kdNr = KdNr
            '  MenuStripSDL.Renderer = New MyRenderer()
        Catch ex As Exception

        End Try

    End Sub
    Private Sub initCboKd()

        Dim connetionString As String = Nothing
        Dim connection As SqlConnection
        Dim command As SqlCommand
        Dim adapter As New SqlDataAdapter()
        Dim ds As New DataSet()
        Dim i As Integer = 0
        Dim sql As String = Nothing
        sql = "SELECT KundenNr,Kurzname FROM Kunden where order by kurzname"
        connection = cSqlDb.GetNewOpenConnection()
        Try
            ' connection.Open()
            command = New SqlCommand(sql, connection)
            adapter.SelectCommand = command
            adapter.Fill(db)
            adapter.Dispose()
            command.Dispose()
            connection.Close()

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



    Private Sub frmKundenUebersichtZOLL_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try

            Me.BER_STUFE = VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("KUNDEN", "SDL")
            timerOP.Interval = 500
            timerOP.Enabled = False


            Try
                Select Case BER_STUFE
                    Case 99 : Me.FindForm.Close() : Exit Sub
                End Select

            Catch ex As Exception

            End Try


            '  KdSearchBox1.initKdBox(Me, lblKdNr)

            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 False Then
                If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("SEE_ALL_COMPANY_INFO", "SDL") Then
                    cboFirmaFMZOLL.fillWithSQL("SELECT cast([Firma_ID] as varchar(3)) as Firma_ID,[Firma_Bez]  FROM [tblFirma] ", True, "FMZOLL", True)
                    cboFirmaFMZOLL.changeItem(VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA_ID)
                Else

                    Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                        Case "VERAG"
                            cboFirmaFMZOLL.fillWithSQL("SELECT cast([Firma_ID] as varchar(3)) as Firma_ID,[Firma_Bez]  FROM [tblFirma] WHERE Firma_ID <> 7", True, "FMZOLL", True)
                        Case "ATILLA"
                            cboFirmaFMZOLL.fillWithSQL("SELECT cast([Firma_ID] as varchar(3)) as Firma_ID,[Firma_Bez]  FROM [tblFirma] WHERE Firma_ID = 7", True, "FMZOLL", True)
                        Case Else 'Beide
                            cboFirmaFMZOLL.fillWithSQL("SELECT cast([Firma_ID] as varchar(3)) as Firma_ID,[Firma_Bez]  FROM [tblFirma] ", True, "FMZOLL", True)
                    End Select

                    If VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA_ID > 0 Then
                        cboFirmaFMZOLL.changeItem(VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA_ID)
                        cboFirmaFMZOLL.Enabled = False
                    End If
                End If
            End If


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

            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("KUNDEN_Vorauskasse_anzeigen", "SDL") Then
                txtVorauskasse.Visible = True
                lblVorkasse.Visible = True
            End If
            If True Then 'VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("KUNDEN_Verwaltung", "SDL") Then
                btnThereforeKundeninfo.Visible = True
            End If


            cboVertrag.fillWithSQL("SELECT kva_id,kva_Bezeichnung  FROM [tblKundenVertraegeArten] ORDER BY kva_Bezeichnung", False, "FMZOLL", True)

            'txtT1VerzollungsadresseBestimmungszollstelle.initSearchBox(Me.FindForm, "[basncd_dstnr] ,[basncd_dstnr] as Nr,[basncd_name]  as Dienststelle,[basncd_alpha] as Land,[basncd_dstnr] +' - ' + [basncd_name] +' (' +[basncd_alpha]+')' as display FROM basncd", {" [basncd_dstnr]", "basncd_name"}, " [basncd_gbdat] >= getdate() ", " basncd_alpha,[basncd_name]", "basncd_dstnr", "display", "ATLAS", , 400, 200, {"display", "basncd_dstnr"})
            txtT1VerzollungsadresseBestimmungszollstelle.initSearchBox(Me.FindForm, "[Code] ,[Code] as Nr,Description as Dienststelle,left(Code,2) as Land,[Description] +' (' +left(Code,2)+')' as display FROM [tbl_DY_ZollDE_C0141_Zollstellen]", {" [Code]", "Description"}, " (StartDate is null OR StartDate< GETDATE()) AND (EndDate is null OR EndDate> GETDATE()) ", " left(Code,2),[Description]", "Code", "display", "FMZOLL", , 400, 200, {"display", "Code"})
            txtGGDatum._value = Now.ToShortDateString


            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("VERIMEX", "AVISO") Then
                Try

                    tbWeitereKundenDetails.TabPages.Remove(tbUmsatz)
                    If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OP_LISTE", "SDL") Then
                        tbWeitereKundenDetails.TabPages.Remove(tbOffenePosten)
                    End If
                    tbcntrAllg.TabPages.Remove(tbAvisoMail)
                    tbcntrAllg.TabPages.Remove(tbKdSpez)
                Catch ex As Exception
                    VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
                End Try
            End If


            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("KUNDEN_Besonderheiten_Bearbeiten", "SDL") Then
                btnPunkt2Save.Visible = True
                rtbAbf_Besonderheiten.ReadOnly = False
            End If
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("KUNDEN_QSTeams_Bearbeiten", "SDL") Then
                btnVeragAnspr.Visible = True
            End If


            pnlSperre.Enabled = VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTEN_SPERRE", "SDL")



            If kdNr > 0 Then setKD(kdNr)

            Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                Case "ATILLA"
                    btncheckliste.Visible = False
                    tbcntrAllg.Visible = False
                Case "IMEX"
                    btnThereforeTarifNr.Visible = True
                    '     btnThereforeTarifNr.Visible = False
                    btnThereforeKundeninfo.Visible = True
                    'btnThereforeKundeninfo.Visible = False

            End Select


            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("UID_EORI_Prüfung", "SDL") Then
                If Not VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "IMEX" Then
                    Button1.Visible = True
                    Button5.Visible = True
                    Button10.Visible = True
                    Button2.Visible = True
                End If
                If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("ADMINFUNCTIONS", "SDL") Then Button3.Visible = True 'Geht nochn nicht
                Button4.Visible = True
            End If

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

    Sub initKD()
        Dim kdsrch As New SDL.frmKundenSuche
        kdsrch.erweitern = True
        If kdsrch.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then

            setKD(kdsrch.kundenNrSearch.Text)
        Else
            Me.BringToFront()
            If kdNr <= 0 Then
                '  Me.Close()
            End If
        End If


    End Sub

    Public Sub setKD(kdnr)
        Me.kdNr = kdnr
        loaded = False
        If Not (New kundenSQL).existByKdNr(kdnr) Then

            initAbfVerb(False)
            rtbInfo.Visible = False
            Exit Sub
            'MsgBox("Keine Kundennummer ausgewählt!", vbCritical)
            'Me.Close() : Exit Sub
        End If
        'MsgBox(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM & " - " & VERAG_PROG_ALLGEMEIN.cAllgemein.USR_NNAME)
        lblTESTSystem.Visible = VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM


        initAllgemein()

        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("VERIMEX", "AVISO") Then
            Try
                tbWeitereKundenDetails.TabPages.Remove(tbUmsatz)
                tbWeitereKundenDetails.TabPages.Remove(tbOffenePosten)
            Catch ex As Exception

            End Try
            If ADRESSE IsNot Nothing AndAlso ADRESSE.LandKz = "TR" Then
                tbWeitereKundenDetails.TabPages.Add(tbUmsatz)
                tbWeitereKundenDetails.TabPages.Add(tbOffenePosten)
                  ElseIf VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OP_LISTE", "SDL") Then
                tbWeitereKundenDetails.TabPages.Remove(tbOffenePosten)
            End If
        End If



        initDGVUmsatz()
        initDGVOffenePosten()
        initDGVVollmachten()
        initDGVGestGarantie()
        initDGVVertraege()
        'initDGVOfferte()
        initDGVAnhaenge()
        initDGVOffertenSperrliste()
        initSperre()


        RG_MONAT = CDate("01." & Now.Month & "." & Now.Year) '.AddMonths(-1)

        tbKontakt_TabIndexChanged(tbKontakt, New EventArgs)

        'If tbcntrKundenDaten.SelectedIndex = 1 Then initZollTarife() ' nur wenn der Tab aktiv, sonst dauert das Laden länger
        'If tbcntrKundenDaten.SelectedIndex = 3 Then initStatistik() ' nur wenn der Tab aktiv, sonst dauert das Laden länger

        ' btncheckliste.Focus()
        loaded = True
    End Sub

    Private Sub pnlAbfVerb_MouseHover(sender As Object, e As EventArgs) Handles rtbInfo.MouseHover, lblAbfertigungsverbot.MouseHover
        Dim p As New UserControl
        '  rtbInfo.Width = 450
        rtbInfo.Height = 300
        ' rtbInfo.Text = abfertigungsverbotText
        rtbInfo.Visible = True
    End Sub

    Private Sub lblAbfertigungsverbot_MouseLeave(sender As Object, e As EventArgs) Handles rtbInfo.MouseLeave, lblAbfertigungsverbot.MouseLeave

        ' rtbInfo.Visible = False
        rtbInfo.Height = 26
    End Sub

    Private Sub lblAbfertigungsverbot_Click(sender As Object, e As EventArgs) Handles lblAbfertigungsverbot.Click
        showForm(abfertigungsverbotText, "Abfertigungsverbot")
    End Sub


    Sub initAllgemein()
        Try
            lblAbfertigungsverbot.Visible = False
            rtbInfo.Visible = False
            trennungBesonderheiten = False

            abfertigungsverbotText = ""
            gespraechsberichtText = ""
            korrAdresseText = ""
            firmenwortlautFiskal = ""
            'Me.dataAdapterFirma = Nothing
            ' Me.dataFirma.Clear()
            'SDL!

            Dim conn As SqlConnection = cSqlDb.GetNewOpenConnectionFMZOLL()
            '    MsgBox(conn.ConnectionString)
            ' Me.dataAdapterFirma = New SqlDataAdapter("SELECT TOP 1 * FROM Kunden INNER JOIN Adressen ON Kunden.KundenNr= Adressen.AdressenNr where  KundenNr=" & kdNr & " AND [Auswahl]='A' ", conn)
            KUNDE = New VERAG_PROG_ALLGEMEIN.cKunde(kdNr)
            ADRESSE = New VERAG_PROG_ALLGEMEIN.cAdressen(kdNr)
            KUNDE_ERW = New VERAG_PROG_ALLGEMEIN.cKundenErweitert(kdNr)
            AUFSCHUB = VERAG_PROG_ALLGEMEIN.cKundenAufschubkonten.LOAD_ListAufschubKTOByKdNr(kdNr)
            '  Me.dataAdapterFirma.Fill(Me.dataFirma)
            conn.Close()

            dgvOfferteDetailsUebersicht.Visible = True
            dgvOffenePosten.Visible = True
            dgvUmsatzbericht.Visible = True
            usrCntlAnhaenge.Visible = True
            rtbAbf_Besonderheiten.Visible = True
            Dim KdFirma = VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale(KUNDE.FilialenNr)
            If KdFirma <> VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA Then
                lblFirma.Text = KdFirma
                lblFirma.Visible = True
                If Not (KdFirma = "IMEX" And VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("AVISO_IMEX", "AVISO")) Then
                    If Not VERAG_PROG_ALLGEMEIN.cAllgemein.isCLUSTER Then
                        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_CLUSTER", "SDL") And
                             Not ((KdFirma = "IMEX" Or KdFirma = "VERAG" Or KdFirma = "VERIMEX") And VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_VERAGIMEX", "SDL")) Then
                            dgvOfferteDetailsUebersicht.Visible = False
                            dgvOffenePosten.Visible = False
                            dgvUmsatzbericht.Visible = False
                            usrCntlAnhaenge.Visible = False
                            rtbAbf_Besonderheiten.Visible = False
                        End If
                    End If
                End If

                If (VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA = "VERIMEX" AndAlso ADRESSE IsNot Nothing AndAlso ADRESSE.LandKz = "TR") Or VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OP_LISTE", "SDL") Then
                    dgvOffenePosten.Visible = True
                End If
            Else
                lblFirma.Visible = False
            End If
            ' Me.dataFirma.AcceptChanges()
            ' Me.dataFirma.Locale = System.Globalization.CultureInfo.InvariantCulture

            lblKdNr.Text = checkNullStr(KUNDE.KundenNr)
            txtDebitorennr.Text = checkNullStr(KUNDE.KundenNrZentrale)


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

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

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


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

            lblInaktiv.Visible = False
            If ADRESSE.Auswahl IsNot Nothing Then
                lblInaktiv.Visible = (ADRESSE.Auswahl = "I")
            End If



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

            lblSteuernummer.Text = ""
            If checkNullStr(ADRESSE.Steuernummer) <> "" Then
                lblSteuernummer.Text = checkNullStr(ADRESSE.Steuernummer)
            End If

            lblEORI.Text = ""
            If checkNullStr(KUNDE.EORITIN) <> "" Then
                lblEORI.Text = (checkNullStr(KUNDE.EORITIN) & " " & checkNullStr(KUNDE.EORITIN_NL)).Trim
            End If
            If lblEORI.Text = "" Then Button4.Visible = False : Button3.Visible = False : Button2.Visible = False
            If lblUid.Text = "" Then Button1.Visible = False : Button5.Visible = False : Button10.Visible = False

            lblZnv.Text = ""
            If checkNullStr(KUNDE.ZulassungsNr_ZnV) <> "" Then
                lblZnv.Text = checkNullStr(KUNDE.ZulassungsNr_ZnV)
            End If

            lblAufEust.Text = ""
            If checkNullStr(KUNDE.Aufschubkonto_EUSt) <> "" Then
                lblAufEust.Text = checkNullStr(KUNDE.Aufschubkonto_EUSt)
            End If

            lblAufZoll.Text = ""
            If checkNullStr(KUNDE.Aufschubkonto_Zoll) <> "" Then
                lblAufZoll.Text = checkNullStr(KUNDE.Aufschubkonto_Zoll)
            End If

            lblAnsprechpartner.Text = ""
            If checkNullStr(ADRESSE.Ansprechpartner) <> "" Then
                lblAnsprechpartner.Text = If(ADRESSE.Anrede IsNot Nothing, ADRESSE.Anrede & " ", "") & checkNullStr(ADRESSE.Ansprechpartner)
            End If
            If checkNullStr(KUNDE.Abfertigungsverbot_Grund) <> "" Then
                abfertigungsverbotText = checkNullStr(KUNDE.Abfertigungsverbot_Grund)
            End If
            rtbInfo.Text = abfertigungsverbotText

            gespraechsberichtText = checkNullStr(KUNDE.Gesprächsbericht)
            lklGanzerText.Visible = False
            lblNoGespr.Visible = True

            If (checkNullStr(KUNDE.Gesprächsbericht) <> "") Then
                lklGanzerText.Visible = True
                lblNoGespr.Visible = False
            End If

            lblKorrAdresse.Visible = False
            lblFwlFiskal.Visible = False
            If (checkNullStr(KUNDE.KD_Korrespondenz) <> "") Then
                korrAdresseText = checkNullStr(KUNDE.KD_Korrespondenz)
                lblKorrAdresse.Visible = True
            End If
            ' txtAbweichndeFiskalAdresse.Text = ""
            If (checkNullStr(KUNDE_ERW.kde_FirmenwortlautFiskal) <> "") Then
                firmenwortlautFiskal = checkNullStr(KUNDE_ERW.kde_FirmenwortlautFiskal)
                '    txtAbweichndeFiskalAdresse.Text = firmenwortlautFiskal
                lblFwlFiskal.Visible = True
            End If


            Dim abfertigungsverbot As Boolean = checkNullBool(KUNDE.Abfertigungsverbot)
            initAbfVerb(abfertigungsverbot)
            Dim TMPText = checkNullStr(KUNDE.Besonderheiten)
            '  TMPText = TMPText.Replace("/ ", "" & vbNewLine)
            '   TMPText = TMPText.Replace("/", "" & vbNewLine)
            rtbAbf_Besonderheiten.Text = TMPText

            ' lblKreditlimit.BackColor = Color.White
            lblKreditlimit.Text = checkNullNbr(KUNDE.Kreditlimit).ToString("C", CultureInfo.CurrentCulture)
            If KUNDE.Kreditlimit <> 0 And KUNDE.Kreditlimit <> 2600 Then
                '  lblKreditlimit.BackColor = Color.Yellow
            End If

            If KUNDE.Kreditlimit = 0 Then lblKreditlimit.Text = ""
            If KUNDE.Kreditlimit = 2600 Then lblKreditlimit.Text = ""

            'lblAviso.Font = f_norm
            'lblNeutralisierung.Font = f_norm
            'txtVorauskasse.Font = f_norm
            lblAviso.BackColor = Color.White
            txtNeutralisierung.BackColor = Color.White
            txtVorauskasse.BackColor = Color.White



            Select Case checkNullStr(KUNDE.Avis)
                Case 0 : lblAviso.Text = "NEIN"
                Case 1 : lblAviso.Text = "Voravis" : lblAviso.BackColor = Color.Yellow ' lblAviso.Font = f_bold
                Case 2 : lblAviso.Text = "Nachavis" : lblAviso.BackColor = Color.Yellow  ' lblAviso.Font = f_bold
                Case 3 : lblAviso.Text = "Vor- und Nachavis" : lblAviso.BackColor = Color.Yellow  ' lblAviso.Font = f_bold
            End Select
            Select Case checkNullStr(KUNDE.Neutralisierung)
                Case 0 : txtNeutralisierung.Text = "NEIN"
                Case 1 : txtNeutralisierung.Text = "JA" : txtNeutralisierung.BackColor = Color.Yellow  'lblNeutralisierung.Font = f_bold
                Case 2 : txtNeutralisierung.Text = "nur in Sonderfällen" : txtNeutralisierung.BackColor = Color.Yellow  'lblNeutralisierung.Font = f_bold
            End Select
            Select Case checkNullStr(KUNDE.Neutralisierung)
                Case 0 : txtNeutralisierung.Text = "NEIN"
                Case 1 : txtNeutralisierung.Text = "JA" : txtNeutralisierung.BackColor = Color.Yellow  'lblNeutralisierung.Font = f_bold
                Case 2 : txtNeutralisierung.Text = "nur in Sonderfällen" : txtNeutralisierung.BackColor = Color.Yellow  'lblNeutralisierung.Font = f_bold
            End Select




            If KUNDE.Vorkasse Then
                txtVorauskasse.Text = "JA"
                txtVorauskasse.BackColor = Color.Yellow
            Else
                txtVorauskasse.Text = ""
                txtVorauskasse.BackColor = Color.White
            End If

            lblVorkasse.BackColor = txtVorauskasse.BackColor
            lblNeutralisierung.BackColor = txtNeutralisierung.BackColor

            If KUNDE_ERW.kde_KundeFremdspedition Then
                txtVerzolltBei.Text = If(KUNDE_ERW.kde_verzolltBei, "FREMD")
                txtVerzolltBei.BackColor = Color.Yellow
            Else
                txtVerzolltBei.Text = ""
                txtVerzolltBei.BackColor = Color.WhiteSmoke
            End If

            If KUNDE_ERW.kde_KundeFremdspeditionExport Then
                txtVerzolltBeiExport.Text = If(KUNDE_ERW.kde_verzolltBeiExport, "FREMD")
                txtVerzolltBeiExport.BackColor = Color.Yellow
            Else
                txtVerzolltBeiExport.Text = ""
                txtVerzolltBeiExport.BackColor = Color.WhiteSmoke
            End If


            cbxFiskalabfertigung.Checked = checkNullBool(KUNDE.Fiskal)
            cbxFiskalabfertigung.CheckedValue = checkNullBool(KUNDE.Fiskal)
            '
            '  lblZollvollmacht.Text = "NEIN"
            '   lblZVMErneuern.Visible = False
            '   lblZollvollmacht.ForeColor = Color.Black
            ''   If checkNullBool(KUNDE.Zollvollmacht)) Then
            '  lblZollvollmacht.Text = ""
            'If checkNullStr(KUNDE.Zollvollmacht vom)) <> "" Then
            '   lblZollvollmacht.Text &= "vom " & checkNullStr(KUNDE.Zollvollmacht vom))
            '   Try
            'If CDate(checkNullStr(KUNDE.Zollvollmacht vom))) < CDate("01." & Now.Month & "." & Now.Year).AddYears(-2) Then
            'lblZVMErneuern.Visible = True
            '   lblZollvollmacht.ForeColor = Color.Red
            '  End If
            ' Catch ex As Exception : End Try
            '     End If
            '  End If



            If ADRESSE.LandKz = "AT" Or ADRESSE.LandKz = "A" Then
                lblBonitaet.Text = If(KUNDE_ERW.kde_CreditSaveBonitaetsScore, "")
            Else
                lblBonitaet.Text = If(KUNDE_ERW.kde_CreditSaveBonitaetsIndex, "")
            End If

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

            lblBonitaetRisikostufe.Text = If(KUNDE_ERW.kde_CreditSaveBonitaetsklasse, "")
            If lblBonitaetRisikostufe.Text = "" Then

                lblBonitaetRisikostufe.Text = If(KUNDE_ERW.kde_BonitaetsStufe, "")

            End If


            ' select case backgrounndcolor
            Select Case lblBonitaetRisikostufe.Text
                Case "A", "1"
                    lblBonitaetRisikostufe.BackColor = Color.Green
                    lblBonitaetRisikostufe.ForeColor = Color.White
                Case "B", "2"
                    lblBonitaetRisikostufe.BackColor = Color.LightGreen
                    lblBonitaetRisikostufe.ForeColor = Color.Black
                Case "C", "3"
                    lblBonitaetRisikostufe.BackColor = Color.Yellow
                    lblBonitaetRisikostufe.ForeColor = Color.Black
                Case "D", "4"
                    lblBonitaetRisikostufe.BackColor = Color.Orange
                    lblBonitaetRisikostufe.ForeColor = Color.Black
                Case "E", "5"
                    lblBonitaetRisikostufe.BackColor = Color.Red
                    lblBonitaetRisikostufe.ForeColor = Color.White
                Case "F", "6"
                    lblBonitaetRisikostufe.BackColor = Color.Red
                    lblBonitaetRisikostufe.ForeColor = Color.White

                Case Else
                    lblBonitaetRisikostufe.BackColor = Color.WhiteSmoke
                    lblBonitaetRisikostufe.ForeColor = Color.Black

            End Select



            If lblBonitaet.Text = "0" Then lblBonitaet.Text = ""

            If KUNDE.Bonitätsdatum IsNot Nothing AndAlso IsDate(KUNDE.Bonitätsdatum) Then
                lblBonitaetsdatum.Text = CDate(KUNDE.Bonitätsdatum).ToShortDateString
            Else
                lblBonitaetsdatum.Text = ""
            End If

            lblHoechstkredit._value = If(IsNumeric(If(KUNDE.Höchstkredit, "")), KUNDE.Höchstkredit, "")


            'txtKundenbetreuer.Text = If(KUNDE_ERW.kde_qsTeamMAName, "")
            'txtKundenbetreuerTeam.Text = If(KUNDE_ERW.kde_qsTeamName, "")

            txtKundenbetreuer.Text = VERAGSQL.DLookup("team_bezeichnung", "tblTeams", "[team_id]='" & KUNDE_ERW.kde_TeamId & "'", "ADMIN")
            txtKundenbetreuerTeam.Text = VERAGSQL.DLookup("mit_vname +' '+mit_nname", "tblMitarbeiter", "[mit_id]='" & KUNDE_ERW.kde_TeamMAId & "'", "ADMIN")


            'cbxAbf_SvsRvs.CheckedValue = checkNullBool(KUNDE.SVS)

            'txtAbf_Vorlageprovision._value = checkNullStr(KUNDE.Vorlageprovision)
            'txtAbf_Kreditaufwendungen._value = checkNullStr(KUNDE.Kreditaufwendungen)
            'txtAbf_Bankspesen._value = checkNullStr(KUNDE.Bankspesen)
            'txtAbf_BankspesenMindestbetrag.Text = checkNullStr(KUNDE.Bankspesen_Mindestbetrag)
            'txtAbf_Waehrung.Text = checkNullStr(KUNDE.Währungscode)

            txtSammelrechnung.Text = "NEIN"
            If CInt(KUNDE.Sammelrechnung) > 0 Then
                Select Case CInt(KUNDE.Sammelrechnung)
                    Case 1 : txtSammelrechnung.Text = "1 - täglich"
                    Case 2 : txtSammelrechnung.Text = "2 - halbmonatlich"
                    Case 3 : txtSammelrechnung.Text = "3 - monatlich"
                    Case 4 : txtSammelrechnung.Text = "4 - Dekade"
                    Case 5 : txtSammelrechnung.Text = "5 - wöchentlich"
                    Case 6 : txtSammelrechnung.Text = "6 - Maut/Diesel"
                    Case 7 : txtSammelrechnung.Text = "7 - LKW"
                    Case Else : txtSammelrechnung.Text = "?"
                End Select


            End If



            txtZahlungsziel.Text = If(KUNDE.Zahlungsziel, "-") & " Tage"

            rtbLKWFreigabeSenden.Text = checkNullStr(KUNDE.DokumenteLKWFreigabe)
            cbxKdAuftragsNr.Checked = checkNullBool(KUNDE_ERW.kde_VerwendetAuftragsNr)
            txtFixeKdAtrNr.Text = If(KUNDE_ERW.kde_FixeAuftragsNr, "")
            txtInfoKdAtrNr.Text = If(KUNDE_ERW.kde_InfoAuftragsNr, "")

            UsrCntlKundenAvisoMailBenachrichtigung1.init(KUNDE, KUNDE_ERW)

            'UsrCntlKundenBesonderheiten1.Visible = False
            If KUNDE_ERW.kde_BesonderheitenNeu Then
                UsrCntlKundenBesonderheiten1.Size = rtbAbf_Besonderheiten.Size
                UsrCntlKundenBesonderheiten1.init(kdNr)
                UsrCntlKundenBesonderheiten1.Visible = True
            Else
                UsrCntlKundenBesonderheiten1.Visible = False
            End If
            rtbAbf_Besonderheiten.Visible = Not UsrCntlKundenBesonderheiten1.Visible

            initAufschub()

            Button1.BackgroundImage = My.Resources.fragezeichen
            Button3.BackgroundImage = My.Resources.fragezeichen
            '     Button4.Visible = False
            '  Button5.Visible = False
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Es ist ein Fehler beim Laden der Firmendaten - Allgemein aufgetreten!")
        End Try
    End Sub

    Private Sub FlatButton4_Click(sender As Object, e As EventArgs) Handles FlatButton4.Click
        Try
            Dim kdTmp As New VERAG_PROG_ALLGEMEIN.cKunde(kdNr)
            kdTmp.DokumenteLKWFreigabe = rtbLKWFreigabeSenden.Text
            kdTmp.SAVE()
            Dim kdErwTmp As New VERAG_PROG_ALLGEMEIN.cKundenErweitert(kdNr)
            kdErwTmp.kde_VerwendetAuftragsNr = cbxKdAuftragsNr.Checked
            kdErwTmp.kde_FixeAuftragsNr = If(txtFixeKdAtrNr.Text <> "", txtFixeKdAtrNr.Text, Nothing)
            kdErwTmp.kde_InfoAuftragsNr = If(txtInfoKdAtrNr.Text <> "", txtInfoKdAtrNr.Text, Nothing)

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


    Sub initAbfVerb(abfertigungsverbot)
        If abfertigungsverbot Then
            'Me.BackColor = Color.Red
            lblAbfertigungsverbot.Visible = True
            rtbInfo.Visible = True
            'lblTARIFE.ForeColor = Color.White
        Else
            'Me.BackColor = Color.White
            lblAbfertigungsverbot.Visible = False
            rtbInfo.Visible = False
            'lblTARIFE.ForeColor = Color.FromArgb(0, 54, 128)
        End If
    End Sub


    Sub showForm(t As String, Optional h As String = "")
        Dim f As New Form
        Dim p As New Panel
        Dim rtb As New RichTextBox
        f.StartPosition = FormStartPosition.CenterScreen
        f.Width = 700
        f.Height = 400
        f.Text = h
        f.Icon = My.Resources.sdl_ico
        rtb.Dock = DockStyle.Fill
        p.Dock = DockStyle.Fill
        f.Controls.Add(p)
        p.Controls.Add(rtb)
        rtb.Text = t
        f.ShowDialog()
    End Sub
    Sub initDGVAnhaenge()
        usrCntlAnhaenge.INIT(kdNr)
        tbAnhaenge.Text = "Anhänge"
        '   MsgBox(usrCntlAnhaenge.MyListBox1.Items.Count)
        If usrCntlAnhaenge.MyListBox1.Items.Count > 0 Then tbAnhaenge.Text &= " (" & usrCntlAnhaenge.MyListBox1.Items.Count & ")"
        Exit Sub
        With dgvAnhaenge
            .DataSource = SQL.loadDgvBySql("SELECT [da_id],[da_pfad],[da_name]  FROM [tblDatenarchiv] " &
                                            " WHERE [da_KundenNr]='" & kdNr & "' and [da_kategorie]='DOKUMENTE' AND da_ordner ='ANHÄNGE' ", "FMZOLL")

            .Columns("da_id").Visible = False
            .Columns("da_pfad").Visible = False
            .Columns("da_name").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("da_name").HeaderText = "Datei"
            .ClearSelection()
            AddHandler .CellDoubleClick, Sub()
                                             If dgvAnhaenge.SelectedRows.Count > 0 Then
                                                 dgvAnhaenge.Cursor = Cursors.WaitCursor
                                                 Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(dgvAnhaenge.SelectedRows(0).Cells("da_id").Value)
                                                 DS.OPEN_SINGLE(True)
                                                 dgvAnhaenge.Cursor = Cursors.Default
                                                 'cDATENSERVER.openDataTMPByDatenarchivId(dgvAnhaenge.SelectedRows(0).Cells("da_id").Value)
                                             End If
                                         End Sub

        End With
    End Sub

    Sub initDGVUmsatz()
        With dgvUmsatzbericht
            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

            'Alles andere gesperrt



            Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale(KUNDE.FilialenNr)
                Case "VERAG"
                    where &= " AND Firma_ID <> 7"
                Case "ATILLA"
                    where &= " AND Firma_ID = 7"
            End Select
            .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

    Sub initDGVVollmachten()
        With dgvVollmachten
            .Columns.Clear()
            Dim where = " AND art.kdvma_Firma='" & VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA & "' "

            If VERAG_PROG_ALLGEMEIN.cAllgemein.isCLUSTER Then
                where = " AND art.kdvma_Firma='" & VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale(KUNDE.FilialenNr) & "' "
            End If

            .DataSource = SQL.loadDgvBySql("SELECT * FROM (SELECT abf.kdvm_Id, art.kdvma_Id,  art.kdvma_Bezeichnung, abf.[kdvm_KundenNr], abf.[kdvm_erhalten],abf.[kdvm_erhalten_Datum], abf.[kdvm_gueltig_bis], abf.kdvm_datenarchivId, abf.kdvm_Info, abf.[kdvm_vermerk], abf.[kdvm_archiviert],ROW_NUMBER() OVER(PARTITION BY art.kdvma_Id ORDER BY kdvm_archiviert asc, abf.kdvm_gueltig_bis asc, abf.kdvm_erhalten_Datum desc) RowNumber" &
                                                    "  FROM [tblKundenVollmachtenArt] as art LEFT  JOIN (select * from [tblKundenVollmachten] where [kdvm_KundenNr]='" & kdNr & "' ) as abf on art.[kdvma_Id]=abf.[kdvm_kdvmaId] WHERE art.kdvma_visible=1 AND abf.kdvm_erhalten = 1 AND ISNULL(abf.[kdvm_geloescht],0) != 1 " & where &
                                                    " ) A WHERE RowNumber = 1", "FMZOLL")


            '  .RowTemplate.Height = 30
            .Columns("kdvm_Id").Visible = False
            .Columns("kdvma_Id").Visible = False
            .Columns("kdvm_KundenNr").Visible = False
            .Columns("kdvm_datenarchivId").Visible = False
            .Columns("kdvma_Bezeichnung").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("kdvma_Bezeichnung").HeaderText = "Bezeichnung"
            .Columns("kdvm_erhalten").Visible = False
            .Columns("kdvm_erhalten").Width = 50
            .Columns("kdvm_erhalten").HeaderText = "Erhalten"
            .Columns("kdvm_erhalten").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("kdvm_erhalten_Datum").Width = 80
            .Columns("kdvm_erhalten_Datum").HeaderText = "Gültig von"
            .Columns("kdvm_erhalten_Datum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("kdvm_gueltig_bis").Width = 80
            .Columns("kdvm_gueltig_bis").HeaderText = "Gültig bis"
            .Columns("kdvm_gueltig_bis").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            .Columns("kdvm_Info").Width = 200
            .Columns("kdvm_Info").HeaderText = "Info"
            .Columns("kdvm_Info").Visible = False
            .Columns("kdvm_vermerk").Width = 10
            .Columns("kdvm_vermerk").HeaderText = "Vermerk"
            .Columns("kdvm_vermerk").Visible = False
            .Columns("kdvm_archiviert").Visible = False
            .Columns("RowNumber").Visible = False


            If True Then
                Dim c As New DataGridViewImageColumn
                c.Name = "clmnVermerk" : c.HeaderText = ""
                c.DefaultCellStyle.NullValue = Nothing
                c.ImageLayout = DataGridViewImageCellLayout.Zoom
                c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
                c.DefaultCellStyle.Tag = "" '.Columns("kdvm_vermerk")

                .Columns.Add(c)

                For Each r As DataGridViewRow In .Rows
                    If r.Cells("kdvm_vermerk").Value IsNot DBNull.Value AndAlso r.Cells("kdvm_vermerk").Value IsNot "" Then
                        DirectCast(r.Cells("clmnVermerk"), DataGridViewImageCell).Value = My.Resources.warning2
                        DirectCast(r.Cells("clmnVermerk"), DataGridViewImageCell).ToolTipText = r.Cells("kdvm_vermerk").Value.ToString


                    End If
                Next

            End If

            If True Then

                Dim c As New DataGridViewImageColumn
                c.Name = "clmnTherefore" : c.HeaderText = "PDF"
                '    c.Image = Nothing
                c.DefaultCellStyle.NullValue = Nothing
                c.ImageLayout = DataGridViewImageCellLayout.Zoom
                c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
                c.DefaultCellStyle.Tag = "Therefore anzeigen"

                .Columns.Add(c)

                For Each r As DataGridViewRow In .Rows
                    If r.Cells("kdvma_Id").Value IsNot DBNull.Value AndAlso IsNumeric(r.Cells("kdvma_Id").Value) Then
                        Select Case r.Cells("kdvma_Id").Value
                            Case 1, 7, 2, 8, 4, 9, 12, 13 : DirectCast(r.Cells("clmnTherefore"), DataGridViewImageCell).Value = My.Resources.therefore1
                        End Select
                    End If
                Next


            End If

            If True Then

                Dim c As New DataGridViewImageColumn
                c.Name = "clmnPDF" : c.HeaderText = "PDF"
                c.Image = My.Resources.pdf_gray : c.ImageLayout = DataGridViewImageCellLayout.Zoom
                c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
                c.DefaultCellStyle.Tag = "PDF anzeigen"
                .Columns.Add(c)
            End If


            Dim FirmaTmp = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OFFERTE_FREMD_VERAGIMEX", "SDL") Or VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("FAKTURIERUNG_VERAGIMEX", "SDL") Then
                FirmaTmp = "VERAGIMEX"
            End If

            Select Case FirmaTmp
           ' Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
                Case "UNISPED", "IMEX"
                    .Columns("clmnVermerk").Visible = True
                    .Columns("clmnTherefore").Visible = False
                    .Columns("clmnPDF").Visible = True
                Case "VERAGIMEX"
                    .Columns("clmnVermerk").Visible = True
                    .Columns("clmnTherefore").Visible = True
                    .Columns("clmnPDF").Visible = True
                Case "FRONTOFFICE"
                    .Columns("clmnVermerk").Visible = True
                    .Columns("clmnTherefore").Visible = True
                    .Columns("clmnPDF").Visible = True
                Case Else
                    .Columns("clmnVermerk").Visible = True
                    .Columns("clmnTherefore").Visible = True
                    .Columns("clmnPDF").Visible = True
            End Select
            For Each r As DataGridViewRow In .Rows
                If r.Cells("kdvm_erhalten").Value Is DBNull.Value Then
                    r.DefaultCellStyle.ForeColor = Color.Gray
                ElseIf CBool(r.Cells("kdvm_erhalten").Value) = False Then
                    r.DefaultCellStyle.ForeColor = Color.Gray
                ElseIf IsDate(r.Cells("kdvm_erhalten_Datum").Value) AndAlso CDate(r.Cells("kdvm_erhalten_Datum").Value) < Now.AddYears(-2) Then
                    r.DefaultCellStyle.ForeColor = Color.Red
                End If

                If True Then
                    If r.Cells("kdvm_datenarchivId").Value IsNot DBNull.Value AndAlso CInt(r.Cells("kdvm_datenarchivId").Value) > 0 Then
                        DirectCast(r.Cells("clmnPDF"), DataGridViewImageCell).Value = My.Resources.pdf
                    End If
                End If
            Next
        End With

    End Sub



    Sub initDGVGestGarantie()
        With dgvGestGarantie
            .Columns.Clear()


            .DataSource = VERAG_PROG_ALLGEMEIN.cGestellungsgarantien.LOAD_LIST(kdNr)
            If .Columns.Count = 0 Then Exit Sub

            .Columns("gg_Id").Visible = False
            .Columns("gg_KundenNr").Visible = False
            .Columns("gg_datenarchivId").Visible = False
            .Columns("gg_erhalten_Datum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns("gg_erhalten_Datum").Width = 70
            .Columns("gg_erhalten_Datum").HeaderText = "Datum"
            .Columns("gg_Zollamt").Width = 80
            .Columns("gg_Zollamt").HeaderText = "Zollamt"
            .Columns("gg_Info").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("gg_Info").HeaderText = "Info"


            If True Then
                Dim c As New DataGridViewImageColumn
                c.Name = "clmnPDF" : c.HeaderText = "PDF"
                c.Image = My.Resources.pdf_gray : c.ImageLayout = DataGridViewImageCellLayout.Zoom
                c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
                c.DefaultCellStyle.Tag = "PDF anzeigen"
                .Columns.Add(c)
                For Each r As DataGridViewRow In .Rows
                    If r.Cells("gg_datenarchivId").Value IsNot DBNull.Value AndAlso CInt(r.Cells("gg_datenarchivId").Value) > 0 Then
                        DirectCast(r.Cells("clmnPDF"), DataGridViewImageCell).Value = My.Resources.pdf
                    End If
                Next
            End If
        End With
        clearGG()
    End Sub

    Sub initDGVVertraege()
        With dgvVertraege
            .Columns.Clear()


            .DataSource = VERAG_PROG_ALLGEMEIN.cKundenVertraege.LOAD_LIST(kdNr)
            If .Columns.Count = 0 Then Exit Sub

            .Columns("kv_Id").Visible = False
            .Columns("kv_KundenNr").Visible = False
            .Columns("kv_vertragArtId").Visible = False
            .Columns("kv_datenarchivId").Visible = False
            .Columns("kv_erhalten_Datum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            .Columns("kv_erhalten_Datum").Width = 70
            .Columns("kv_erhalten_Datum").HeaderText = "Datum"
            .Columns("kva_Bezeichnung").Width = 120
            .Columns("kva_Bezeichnung").HeaderText = "Art"
            .Columns("kv_Info").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("kv_Info").HeaderText = "Info"

            .Columns("kv_gueltig").Width = 35
            .Columns("kv_gueltig").HeaderText = "gültig"
            If True Then
                Dim c As New DataGridViewImageColumn
                c.Name = "clmnPDF" : c.HeaderText = "PDF"
                c.Image = My.Resources.pdf_gray : c.ImageLayout = DataGridViewImageCellLayout.Zoom
                c.Width = 40 : c.DefaultCellStyle.Padding = New Padding(2) : c.DefaultCellStyle.BackColor = Color.White
                c.DefaultCellStyle.Tag = "PDF anzeigen"
                .Columns.Add(c)
                For Each r As DataGridViewRow In .Rows
                    If r.Cells("kv_datenarchivId").Value IsNot DBNull.Value AndAlso CInt(r.Cells("kv_datenarchivId").Value) > 0 Then
                        DirectCast(r.Cells("clmnPDF"), DataGridViewImageCell).Value = My.Resources.pdf
                    End If
                Next
            End If
            .ClearSelection()
        End With
        clearKV()
    End Sub

    Sub initDGVOffertenSperrliste()
        With dgvOffertenSperrliste
            Dim where As String = ""
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("VERIMEX", "AVISO") Then
                where = "  AND Offerten.OffertenNr IN (5,6,18,24,32,33,34,37,40,7,8,9,12,13) "
            End If


            '     MsgBox("SELECT Offerten.OffertenNr, cast(Offerten.OffertenNr as varchar(3)) + ' - ' + Offertenstamm.OffertenBez as OffertenBez ,Offerten.Besonderheiten, Gesperrt, Gesperrt_Datum, Gesperrt_Grund FROM Offerten inner join Offertenstamm on [Offerten].OffertenNr=Offertenstamm.OffertenNr WHERE Offerten.KundenNr='" & kdNr & "' " & where & " ORDER BY Offerten.OffertenNr ")
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT Offerten.OffertenNr, cast(Offerten.OffertenNr as varchar(3)) + ' - ' + Offertenstamm.OffertenBez as OffertenBez ,Offerten.Besonderheiten, Gesperrt, Gesperrt_Datum, Gesperrt_Grund FROM Offerten inner join Offertenstamm on [Offerten].OffertenNr=Offertenstamm.OffertenNr WHERE Offerten.KundenNr='" & kdNr & "' " & where & " ORDER BY Offerten.OffertenNr ", "FMZOLL")

            .DataSource = dt

            If .ColumnCount = 0 Then Exit Sub

            .Columns("OffertenNr").Visible = False
            .Columns("Besonderheiten").Visible = False
            ' .Columns("OffertenNr").HeaderText = "Nr"
            .Columns("OffertenBez").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("OffertenBez").HeaderText = "Bezeichnung"
            .Columns("Gesperrt").HeaderText = "Sperre"
            .Columns("Gesperrt").Width = 45
            .Columns("Gesperrt_Datum").HeaderText = "Datum"
            .Columns("Gesperrt_Datum").Width = 100
            .Columns("Gesperrt_Grund").HeaderText = "Sperre-Grund"
            .Columns("Gesperrt_Grund").Width = 320
            .Columns("Gesperrt").Visible = False
            .Columns("Gesperrt_Grund").Visible = False
            .Columns("Gesperrt_Datum").Visible = False

            lblKeineSperren.Visible = (.RowCount = 0)


            For Each r As DataGridViewRow In .Rows
                If r.Cells("Gesperrt").Value IsNot DBNull.Value Then
                    If CBool(r.Cells("Gesperrt").Value) = True Then
                        r.DefaultCellStyle.ForeColor = Color.Red
                    End If
                End If
            Next

            AddHandler dgvOffertenSperrliste.SelectionChanged, Sub()
                                                                   initSperre()
                                                               End Sub


        End With


    End Sub


    Private Sub initSperre()
        cbxSperreSetzen.Checked = False
        txtSperreDat.Text = ""
        txtSperreGrund.Text = ""
        dgvOfferteDetailsUebersicht.Columns.Clear()
        If dgvOffertenSperrliste.SelectedRows.Count > 0 And dgvOffertenSperrliste.Columns.Count > 0 Then
            If dgvOffertenSperrliste.SelectedRows(0).Cells("Gesperrt").Value IsNot DBNull.Value Then
                cbxSperreSetzen.Checked = dgvOffertenSperrliste.SelectedRows(0).Cells("Gesperrt").Value
                txtSperreDat.Text = If(dgvOffertenSperrliste.SelectedRows(0).Cells("Gesperrt_Datum").Value IsNot DBNull.Value, dgvOffertenSperrliste.SelectedRows(0).Cells("Gesperrt_Datum").Value, "")
                txtSperreGrund.Text = dgvOffertenSperrliste.SelectedRows(0).Cells("Gesperrt_Grund").Value
                If dgvOffertenSperrliste.SelectedRows(0).Cells("Gesperrt").Value Then
                    dgvOffertenSperrliste.SelectedRows(0).DefaultCellStyle.SelectionForeColor = Color.Red
                Else
                    dgvOffertenSperrliste.SelectedRows(0).DefaultCellStyle.SelectionForeColor = Color.Black
                End If
            End If
            initDGVOfferteDetailsUebersicht(dgvOffertenSperrliste.SelectedRows(0).Cells("OffertenNr").Value)
        End If


    End Sub


    'Sub initDGVOfferte()
    '    With dgvOfferte
    '        .DataSource = SQL.loadDgvBySql("SELECT Offerten.OffertenNr, cast(Offerten.OffertenNr as varchar(3)) + ' - ' + Offertenstamm.OffertenBez as OffertenBez ,Offerten.Besonderheiten FROM Offerten inner join Offertenstamm on [Offerten].OffertenNr=Offertenstamm.OffertenNr WHERE Offerten.KundenNr='" & kdNr & "' ORDER BY Offerten.OffertenNr ", "FMZOLL")
    '        .Columns("OffertenNr").Visible = False
    '        .Columns("Besonderheiten").Visible = False
    '        ' .Columns("OffertenNr").HeaderText = "Nr"
    '        .Columns("OffertenBez").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    '        .Columns("OffertenBez").HeaderText = "Bezeichnung"
    '    End With
    '    ' initDGVOfferteDetails()


    'End Sub


    'Private Sub dgvOfferte_CellContentClick(sender As Object, e As EventArgs)
    '    dgvOfferteDetails.Columns.Clear()
    '    If dgvOfferte.SelectedRows.Count > 0 Then
    '        initDGVOfferteDetails(dgvOfferte.SelectedRows(0).Cells("OffertenNr").Value)
    '    End If
    'End Sub


    'Sub initDGVOfferteDetails(Optional OffertenNr = -1)
    '    With dgvOfferteDetails
    '        .DataSource = SQL.loadDgvBySql(" SELECT [LeistungsNr],[LeistungsBez],[BerechnungsartNr],[Preis],[Anzahl],[BGebLeistungsNr],[BGebProzent],[BGebMinBetrag],[Eingegeben am],[PreisänderungProzent],[PreisAlt],[Preisänderung],[Geändert am],[Sachbearbeiter] " &
    '                                          " FROM [Offertenpositionen] " &
    '                                       " WHERE KundenNr='" & kdNr & "' and OffertenNr='" & OffertenNr & "' ORDER BY LeistungsNr ", "FMZOLL")

    '        FUNC.dgvCellToCbo(dgvOfferteDetails, 2, "Berechnungsart", "BerechnungsartNr", " SELECT [BerechnungsartNr], CAST(BerechnungsartNr as varchar(3))  + ' - ' + [BerechnungsartBez] as [BerechnungsartBez]  FROM [Berechnungsart] ORDER BY BerechnungsartNr ", "FMZOLL", 150)
    '        FUNC.dgvCellToCbo(dgvOfferteDetails, 5, "BGebLeist.", "BGebLeistungsNr", " SELECT [LeistungsNr], CAST(LeistungsNr as varchar(3)) + ' - ' + [LeistungsBez] as LeistungsBez FROM [Leistungen] ORDER BY [LeistungsNr] ", "FMZOLL", 250)



    '        .Columns("LeistungsNr").Width = 30
    '        .Columns("LeistungsNr").HeaderText = "Nr"
    '        .Columns("LeistungsBez").MinimumWidth = 180
    '        .Columns("LeistungsBez").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
    '        .Columns("LeistungsBez").HeaderText = "Leistung"
    '        .Columns("BerechnungsartNr").MinimumWidth = 130
    '        .Columns("Preis").Width = 60
    '        .Columns("Preis").DefaultCellStyle.Format = "N2"
    '        .Columns("Preis").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
    '        .Columns("Anzahl").Width = 50
    '        .Columns("Anzahl").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
    '        .Columns("BGebLeistungsNr").Width = 60
    '        .Columns("BGebProzent").Width = 55
    '        .Columns("BGebProzent").HeaderText = "BGeb %"
    '        .Columns("BGebProzent").DefaultCellStyle.Format = "P"
    '        .Columns("BGebProzent").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
    '        .Columns("BGebMinBetrag").Width = 60
    '        .Columns("BGebMinBetrag").HeaderText = "BGebMinBetr."
    '        .Columns("BGebMinBetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
    '        .Columns("Eingegeben am").Visible = False
    '        '  .Columns("Sachbearbeiter").Visible = False
    '        '  .Columns("Geändert am").Visible = False
    '        .Columns("Sachbearbeiter").Width = 65
    '        .Columns("Geändert am").Width = 95
    '        .Columns("PreisänderungProzent").Width = 65
    '        .Columns("PreisänderungProzent").HeaderText = "Preisänd.%"
    '        .Columns("PreisänderungProzent").DefaultCellStyle.Format = "P"
    '        .Columns("PreisänderungProzent").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
    '        .Columns("PreisAlt").Width = 60
    '        .Columns("PreisAlt").DefaultCellStyle.Format = "N2"
    '        .Columns("PreisAlt").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
    '        .Columns("Preisänderung").Width = 60
    '        .Columns("Preisänderung").HeaderText = "PreisNeu"
    '        .Columns("Preisänderung").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight

    '    End With

    'End Sub

    Sub initDGVOfferteDetailsUebersicht(OffertenNr)

        With dgvOfferteDetailsUebersicht
            '  .Columns.Clear()
            .DataSource = SQL.loadDgvBySql(" SELECT [LeistungsNr],[LeistungsBez],[Preis],/*[BerechnungsartNr],[Anzahl],[BGebLeistungsNr],[BGebProzent],[BGebMinBetrag],[Eingegeben am],[PreisänderungProzent],[PreisAlt],[Preisänderung],*/[Geändert am],[Sachbearbeiter] " &
                                              " FROM [Offertenpositionen] " &
                                           " WHERE KundenNr='" & kdNr & "' and OffertenNr='" & OffertenNr & "' ORDER BY LeistungsNr ", "FMZOLL")

            '  FUNC.dgvCellToCbo(dgvOfferteDetailsUebersicht, 2, "Berechnungsart", "BerechnungsartNr", " SELECT [BerechnungsartNr], CAST(BerechnungsartNr as varchar(3))  + ' - ' + [BerechnungsartBez] as [BerechnungsartBez]  FROM [Berechnungsart] ORDER BY BerechnungsartNr ", "FMZOLL", 150)
            ' FUNC.dgvCellToCbo(dgvOfferteDetailsUebersicht, 5, "BGebLeist.", "BGebLeistungsNr", " SELECT [LeistungsNr], CAST(LeistungsNr as varchar(3)) + ' - ' + [LeistungsBez] as LeistungsBez FROM [Leistungen] ORDER BY [LeistungsNr] ", "FMZOLL", 250)



            .Columns("LeistungsNr").Width = 30
            .Columns("LeistungsNr").HeaderText = "Nr"
            .Columns("LeistungsBez").MinimumWidth = 180
            .Columns("LeistungsBez").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("LeistungsBez").HeaderText = "Leistung"
            ' .Columns("BerechnungsartNr").MinimumWidth = 130
            .Columns("Preis").Width = 60
            .Columns("Preis").DefaultCellStyle.Format = "N2"
            .Columns("Preis").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
            '.Columns("Anzahl").Width = 50
            '.Columns("Anzahl").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("BGebLeistungsNr").Width = 60
            '.Columns("BGebProzent").Width = 55
            '.Columns("BGebProzent").HeaderText = "BGeb %"
            '.Columns("BGebProzent").DefaultCellStyle.Format = "P"
            '.Columns("BGebProzent").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
            '.Columns("BGebMinBetrag").Width = 60
            '.Columns("BGebMinBetrag").HeaderText = "BGebMinBetr."
            '.Columns("BGebMinBetrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
            '.Columns("Eingegeben am").Visible = False

            .Columns("Sachbearbeiter").Width = 65
            .Columns("Geändert am").Width = 95
            '.Columns("PreisänderungProzent").Width = 65
            '.Columns("PreisänderungProzent").HeaderText = "Preisänd.%"
            '.Columns("PreisänderungProzent").DefaultCellStyle.Format = "P"
            '.Columns("PreisänderungProzent").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
            '.Columns("PreisAlt").Width = 60
            '.Columns("PreisAlt").DefaultCellStyle.Format = "N2"
            '.Columns("PreisAlt").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
            '.Columns("Preisänderung").Width = 60
            '.Columns("Preisänderung").HeaderText = "PreisNeu"
            '.Columns("Preisänderung").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight


        End With

    End Sub


    'Private Sub dgvOfferteDetails_SelectionChanged(sender As Object, e As EventArgs) Handles dgvOfferte.SelectionChanged
    '    If dgvOfferte.RowCount > 0 Then
    '        rtbBesonderheiten.Text = checkNullStr(dgvOfferte.Rows(0).Cells("Besonderheiten").Value)
    '    Else
    '        rtbBesonderheiten.Text = ""
    '    End If

    'End Sub


    Sub initDGVOffenePosten()

        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.getFirmaFromFiliale(KUNDE.FilialenNr)
            Case "IMEX" : initDGVOffenePostenIMEX()
            Case Else : initDGVOffenePostenVERAG()
        End Select
    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

                '        .Columns("KumSaldoEUR").ReadOnly = False

                ' If .RowCount > 0 Then


            End If

            Dim zahlungsziel = 10
            Dim sumZZ As Double = 0
            Dim sumNOTZZ As Double = 0
            Dim sumCredit As Double = 0
            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

            'Dim OP_tmp As Double = 0

            'If cboFirmaFMZOLL._value <> "" Then
            '    If .RowCount > 0 Then OP_tmp = If(.Rows(0).Cells("KumSaldoEUR").Value, 0)
            'End If


            'If OP_tmp > 0 Then
            '    txtOffenePosten.Text = SQL.doSQL("SELECT sum([Saldo])  FROM [Offene_Posten_DVO]  where KundenNr='" & KUNDE.KundenNr & "' ", "FMZOLL")
            'Else
            '    txtOffenePosten.Text = ""
            'End If

            txtOPFaellig.Text = sumZZ.ToString("C")
            If sumZZ > 0 Then
                txtOPFaellig.ForeColor = Color.Red
            Else
                txtOPFaellig.ForeColor = Color.Black
            End If

            txtOPNichtFaellig.Text = sumNOTZZ.ToString("C")
            txtOPNichtFaellig.ForeColor = Color.Black
            'If sumNOTZZ > 0 Then
            '    txtOPNichtFaellig.ForeColor = Color.Red
            'Else
            '    txtOPNichtFaellig.ForeColor = Color.Black
            'End If

            txtOPCredit.Text = sumCredit.ToString("C")
            txtOPCredit.ForeColor = Color.Green
            'If sumCredit < 0 Then
            '    txtOPCredit.ForeColor = Color.Red
            'Else
            '    txtOPCredit.ForeColor = Color.Black
            'End If



            If sumGes <> 0 Then
                txtOffenePosten.Text = sumGes.ToString("C")
                If sumGes < 0 Then
                    txtOffenePosten.ForeColor = Color.Green
                Else
                    txtOffenePosten.ForeColor = Color.Red
                End If
            Else
                txtOffenePosten.Text = ""
            End If
            'If sumGes > 0 Then
            '    txtOffenePosten.Text = sumGes.ToString("C")
            'Else
            '    txtOffenePosten.Text = ""
            'End If


            'Dim c As New DataGridViewTextBoxColumn
            'c.Name = "clmnSaldo"
            'c.HeaderText = "Saldo"
            '.Columns.Insert(6, c)
            ' timerOP.Enabled = True

        End With
        '  Label44.Visible = True
        ' txtOpLeihgeld.Visible = True
        pnl.Visible = True

        Dim op_tmp = SQL.getValueTxtBySql("SELECT isnull(sum(Saldo),0) as OP  FROM [Offene_Posten_DVO] where KundenNr=" & kdNr & " AND konto like '5%'", "FMZOLL")
        If IsNumeric(op_tmp) Then
            txtOpLeihgeld.Text = CDbl(op_tmp).ToString("C2")
        Else
            txtOpLeihgeld.Text = ""
        End If
    End Sub



    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 = ""
            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 [Kontonummer] as KdNr,[Belegdatum] as Datum,[Belegnummer] as Nummer,[Bruttobetrag] as Betrag,[Gesamtausstand] as [OP-Saldo],[Waehrung] as Währung,[KumSaldoEUR] ,[Buchungstext] as Referenz " &
                                                           " FROM [Offene Posten] " &
                                                           " WHERE [Kontonummer]='" & KUNDE.KundenNrZentrale & "' " & where & " ORDER BY OP_ID DESC /*, Belegdatum DESC*/", "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(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 = 60
            .Columns(5).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

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

            .Columns(7).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


            ' If .RowCount > 0 Then
            If OP_tmp <> 0 Then
                ' txtOffenePosten.Text = String.Format("{0:n}", .Rows(0).Cells("KumSaldoEUR").Value)
                'txtOffenePosten.Text = String.Format("{0:n}", OP_tmp)
                txtOffenePosten.Text = OP_tmp.ToString("C")
                If OP_tmp < 0 Then
                    txtOffenePosten.ForeColor = Color.Green
                Else
                    txtOffenePosten.ForeColor = Color.Red
                End If
            Else
                txtOffenePosten.Text = ""
            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
            txtOPFaellig.Text = sumZZ.ToString("C")
            If sumZZ > 0 Then
                txtOPFaellig.ForeColor = Color.Red
            Else
                txtOPFaellig.ForeColor = Color.Black
            End If

            txtOPNichtFaellig.Text = sumNOTZZ.ToString("C")
            txtOPNichtFaellig.ForeColor = Color.Black
            'If sumNOTZZ > 0 Then
            '    txtOPNichtFaellig.ForeColor = Color.Red
            'Else
            '    txtOPNichtFaellig.ForeColor = Color.Black
            'End If

            txtOPCredit.Text = sumCredit.ToString("C")
            txtOPCredit.ForeColor = Color.Green
            'If sumCredit < 0 Then
            '    txtOPCredit.ForeColor = Color.Red
            'Else
            '    txtOPCredit.ForeColor = Color.Black
            'End If

        End With
    End Sub

    Private Sub dgvOffenePosten_RowPostPaint(sender As Object, e As DataGridViewRowPostPaintEventArgs) Handles dgvOffenePosten.RowPostPaint
        If DateDiff(DateInterval.Day, CDate(dgvOffenePosten.Rows(e.RowIndex).Cells("Datum").Value), Now) > If(KUNDE.Zahlungsziel, 10) Then
            If CDbl(dgvOffenePosten.Rows(e.RowIndex).Cells("Betrag").Value) > 0 Then
                dgvOffenePosten.Rows(e.RowIndex).DefaultCellStyle.ForeColor = Color.Red
            End If
        End If
    End Sub


    Public Sub initAufschub()
        '  AUFSCHUB = VERAG_PROG_ALLGEMEIN.cKundenAufschubkonten.LOAD_ListAufschubKTOByKdNr(kdNr)
        dgvAufschub.Rows.Clear()
        If AUFSCHUB IsNot Nothing Then
            For Each AB In AUFSCHUB
                Dim art = ""
                Select Case AB.kdAkto_art
                    Case "10" : art = "10 - ZOLL/EUST"
                    Case "15" : art = "15 - ZOLL"
                    Case "20" : art = "20 - EUST"
                End Select
                dgvAufschub.Rows.Add(AB.kdAkto_id, art, AB.kdAkto_hauptzollamt, AB.kdAkto_kontonummer, AB.kdAkto_eori, AB.kdAkto_eoriNL, AB.kdAkto_bin)
            Next
        End If
        dgvAufschub.ClearSelection()
    End Sub

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


    Function checkNullNbr(o As Object) As Double
        If Not IsDBNull(o) AndAlso IsNumeric(o) Then
            Return o
        End If
        Return 0
    End Function
    Function checkNullBool(o As Object) As Boolean
        Try
            Return DirectCast(o, Boolean)
        Catch ex As Exception
            Return False
        End Try
    End Function



    Private Sub lklGanzerText_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lklGanzerText.LinkClicked
        showForm(gespraechsberichtText, "Gesprächsbericht")
    End Sub

    Private Sub lblEmail_Click(sender As Object, e As EventArgs) Handles lblEmail2.Click, lblEmail.Click

        If sender.text <> "" Then
            If MsgBox("Möchten Sie eine E-Mail an '" & sender.text & "' senden?", vbQuestion + vbYesNo) = vbYes Then
                Try : Process.Start(String.Format("mailto:{0}", sender.text)) : Catch : End Try
            End If
        End If
    End Sub


    Dim tmprowindex As Integer = -1
    Private Sub DgvDelays_CellMouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgvVollmachten.CellMouseDown
        Exit Sub
        Try
            If e.Button = Windows.Forms.MouseButtons.Right Then
                tmprowindex = e.RowIndex
                '  cntxtVollmachten.Show(dgvVollmachten, dgvVollmachten.PointToClient(Cursor.Position))
            End If
        Catch ex As Exception
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        End Try
    End Sub

    '
    Private Sub dgvGestGarantie_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvGestGarantie.CellDoubleClick
        If dgvGestGarantie.SelectedRows.Count = 1 Then
            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(dgvGestGarantie.SelectedRows(0).Cells("gg_datenarchivId").Value)
            DS.OPEN_SINGLE()
        End If
    End Sub

    Private Sub dgvVertraege_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvVertraege.CellDoubleClick
        If dgvVertraege.SelectedRows.Count = 1 Then
            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(dgvVertraege.SelectedRows(0).Cells("kv_datenarchivId").Value)
            DS.OPEN_SINGLE()
        End If
    End Sub


    Private Sub dgvVollmachten_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvVollmachten.CellDoubleClick
        Dim tmprowindex As Integer = e.RowIndex
        If dgvVollmachten.Columns(e.ColumnIndex).Name = "clmnPDF" Then

            If dgvVollmachten.Rows(e.RowIndex).Cells("kdvm_datenarchivId").Value IsNot DBNull.Value AndAlso CInt(dgvVollmachten.Rows(e.RowIndex).Cells("kdvm_datenarchivId").Value) > 0 Then
                ' cDATENSERVER.openDataTMPByDatenarchivId(dgvVollmachten.Rows(e.RowIndex).Cells("kdvm_datenarchivId").Value)
                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(dgvVollmachten.Rows(e.RowIndex).Cells("kdvm_datenarchivId").Value)
                DS.OPEN_SINGLE(True)
            End If
        Else

            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kundendaten_bearbeiten", "SDL") Or
                 VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kunden_VM_bearbeiten", "SDL") Then

                If tmprowindex < 0 Then Exit Sub
                Dim frmGrayOut = cProgramFunctions.grayoutForm(Me)
                'Dim datum = IIf(dgvVollmachten.Rows(tmprowindex).Cells("kdvm_erhalten_Datum").Value Is DBNull.Value, Now, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_erhalten_Datum").Value)
                'Dim gueltigBis = IIf(dgvVollmachten.Rows(tmprowindex).Cells("kdvm_gueltig_bis").Value Is DBNull.Value, Nothing, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_gueltig_bis").Value)
                'Dim l As New frmKundenZOLLVollmachten(kdNr, dgvVollmachten.Rows(tmprowindex).Cells("kdvma_Id").Value, dgvVollmachten.Rows(tmprowindex).Cells("kdvma_Id").Value, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_erhalten").Value, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_archiviert").Value, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_erhalten_Datum").Value, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_gueltig_bis").Value, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_vermerk").Value, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_datenarchivId").Value)
                Dim l As New frmKundenZOLLVollmachten(kdNr, dgvVollmachten.Rows(tmprowindex).Cells("kdvma_Id").Value) '
                If l.ShowDialog(frmGrayOut) = DialogResult.OK Then
                    l.initDGVVollmachtenEmbedded(False)
                    'initDGVVollmachten()
                End If
                frmGrayOut.Close()
                initDGVVollmachten()

            End If
        End If

    End Sub



    Private Sub dgvVollmachten_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvVollmachten.CellClick
        Dim tmprowindex As Integer = e.RowIndex

        Select Case VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA
            Case "VERAG", "FRONTOFFICE"
                If tmprowindex >= 0 Then
                    If dgvVollmachten.Columns(e.ColumnIndex).Name = "clmnTherefore" Then
                        If dgvVollmachten.Rows(e.RowIndex).Cells("kdvma_Id").Value Is DBNull.Value Then Exit Sub
                        If dgvVollmachten.Rows(e.RowIndex).Cells("kdvma_Id").Value Is Nothing Then Exit Sub
                        cProgramFunctions.openThereforeNavigatorZollvollmachten(kdNr, dgvVollmachten.Rows(e.RowIndex).Cells("kdvma_Id").Value)
                    End If
                End If
        End Select
    End Sub




    Private Sub dgvUmsatzbericht_SelectionChanged(sender As Object, e As EventArgs) Handles dgvVollmachten.SelectionChanged, dgvUmsatzbericht.SelectionChanged, dgvOfferteDetailsUebersicht.SelectionChanged, dgvOffenePosten.SelectionChanged  ', dgvOffertenSperrliste.SelectionChanged
        sender.ClearSelection()
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblKorrAdresse.LinkClicked
        showForm(korrAdresseText, "Korrespondenz - Postadresse ")
    End Sub



    Private Sub dgvUmsatzbericht_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvUmsatzbericht.CellDoubleClick
        'MsgBox(e.RowIndex)
        If e.RowIndex < 0 Then Exit Sub
        Dim frmKundenUebersichtZollRg As New frmKundenUebersichtZollRg
        frmKundenUebersichtZollRg.kdNr = dgvUmsatzbericht.Rows(e.RowIndex).Cells("KundenNr").Value
        frmKundenUebersichtZollRg.jahr = dgvUmsatzbericht.Rows(e.RowIndex).Cells("Jahr").Value
        frmKundenUebersichtZollRg.Show()

    End Sub



    Private Sub dgvVollmachten_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvVollmachten.CellDoubleClick
        With dgvVollmachten
            If .SelectedRows.Count > 0 Then
                If Not .SelectedRows(0).Cells("kdvm_datenarchivId") Is DBNull.Value AndAlso IsNumeric(.SelectedRows(0).Cells("kdvm_datenarchivId")) Then
                    'cDATENSERVER.openDataTMPByDatenarchivId(.SelectedRows(0).Cells("kdvm_datenarchivId"))
                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(.SelectedRows(0).Cells("kdvm_datenarchivId"))
                    DS.OPEN_SINGLE(True)

                End If
            End If
        End With
    End Sub


    Private Sub btnAddAttach_Click(sender As Object, e As EventArgs) Handles btnAddAttach.Click
        'cDATENSERVER.uploadDataToDATENSERVERFileDialog("DOKUMENTE", "ANHÄNGE", kdNr)
        Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "ANHÄNGE", "", "", "", "Zoll_Kunde_Anhang", kdNr)
        DS.uploadDataToDATENSERVERFileDialog()
        initDGVAnhaenge()
    End Sub


    Private Sub dgvAnhaenge_KeyUp(sender As Object, e As KeyEventArgs) Handles dgvAnhaenge.KeyUp
        If e.KeyCode = Keys.Delete Then
            If dgvAnhaenge.SelectedRows.Count > 0 Then
                If vbYes = MsgBox("Möchten Sie die Datei wirklich löschen?", vbYesNoCancel) Then
                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER(dgvAnhaenge.SelectedRows(0).Cells("da_id").Value)
                    DS.DELETE_COMPLETE()

                    'cDATENSERVER.deleteFileByDatenarchivId(dgvAnhaenge.SelectedRows(0).Cells("da_id").Value)
                    initDGVAnhaenge()
                End If
            End If
        End If
    End Sub




    Private Sub FlatButton2_Click_1(sender As Object, e As EventArgs) Handles btncheckliste.Click
        'MsgBox("Bitte vorübergehend die Funktion 'UID' im Hauptmenü verwenden!")
        '  Exit Sub
        'If Not cbxFiskalabfertigung.Checked Then
        ' lblFisk.Visible = True
        ' Else
        Dim found = False
        Dim sperre = True
        For Each r As DataGridViewRow In dgvOffertenSperrliste.Rows
            If r.Cells("OffertenNr").Value = "26" Or r.Cells("OffertenNr").Value = "27" Then
                found = True
                If r.Cells("Gesperrt").Value Is DBNull.Value OrElse Not CBool(r.Cells("Gesperrt").Value) Then
                    sperre = False
                End If
            End If
        Next
        If found And sperre Then 'es wurde keine Fikale ohne Sperre gefunden, jedoch welche mit sperre -> Abbruch
            Exit Sub
        End If
        If Not found Then
            If vbYes = MsgBox("Der Kunde hat kein Fiskal-Offert, soll die Checkliste trotzdem geföffnet werden?", vbYesNoCancel) Then
                found = True
            End If
        End If

        If found Then
            Dim frmCheckliste As New frmCheckliste
            frmCheckliste.ADRESSEN = ADRESSE
            frmCheckliste.KUNDE = KUNDE
            frmCheckliste.KUNDE_ERW = KUNDE_ERW

            '     frmCheckliste.kdNr = kdNr
            ' frmCheckliste.userfullname = userfullname
            frmCheckliste.Show()
            Exit Sub
            '   Else
            '    MsgBox("Der Kunde hat hat Fiskal-Offert bzw. ist für die Abfertigungsart gesperrt.")
        End If


        '  End If
    End Sub





    Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click
        Dim frmKundenChangeMail As New frmKundenChangeMail
        frmKundenChangeMail.txtKdNr.Text = lblKdNr.Text
        frmKundenChangeMail.txtKdName.Text = lblFirmenname1.Text
        'KdSearchBox1.Text
        ' frmKundenChangeMail.txtSB.Text = userfullname
        frmKundenChangeMail.Show()
    End Sub


    Private Sub lblEmail_TextChanged(sender As Object, e As EventArgs) Handles lblEmail2.TextChanged, lblEmail.TextChanged
        sender.cursor = IIf(sender.text <> "", Cursors.Hand, Cursors.Default)
    End Sub



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

    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If ADRESSE.UstIdNr Is Nothing Then Exit Sub
        If ADRESSE.UstIdKz Is Nothing Then Exit Sub
        If ADRESSE.UstIdKz = "" Then Exit Sub
        If ADRESSE.UstIdNr = "" Then Exit Sub

        sender.BackgroundImage = My.Resources.wait
        ' Button5.Visible = False


        Dim FO As New VERAG_PROG_ALLGEMEIN.cFinanzOnlineWebService
        FO.initValues()

        If FO.Call_Web_Service_MethodUID_Login_NEU2020() = 0 Then
            Dim UID_TMP = FO.Call_Web_Service_MethodUID_Abfrage_NEU2020(ADRESSE.AdressenNr,, , , 2)
            If UID_TMP IsNot Nothing Then
                If UID_TMP.uid_valid Then
                    setKD(kdNr)
                    sender.BackgroundImage = My.Resources.ok
                Else
                    sender.BackgroundImage = My.Resources.del
                End If
            Else
                sender.BackgroundImage = My.Resources.fragezeichen
            End If

            FO.Call_Web_Service_MethodUID_Logout_NEU2020()

        End If

        ''  If cProgramFunctions.validUID(ADRESSE.UstIdKz, ADRESSE.UstIdNr) Then
        'Dim UID = VERAG_PROG_ALLGEMEIN.cUIDPruefung.doUIDPruefung(ADRESSE.AdressenNr, True)
        'If UID IsNot Nothing Then
        '    If UID.uid_valid Then
        '        setKD(kdNr)
        '        sender.BackgroundImage = My.Resources.ok
        '    Else
        '        sender.BackgroundImage = My.Resources.del
        '    End If
        'Else
        '    sender.BackgroundImage = My.Resources.fragezeichen
        'End If


    End Sub

    Private Sub btnPruf_Click(sender As Object, e As EventArgs) Handles Button3.Click
        'Create an object that calls the name for the 
        'Web service used in the added Web Reference. 

        sender.BackgroundImage = My.Resources.wait
        ' Button4.Visible = False
        Dim sGetValu2e As New validation
        ' sGetValu2e.Url = "http://eori.ws.eos.dds.s/"
        sGetValu2e.RequestEncoding = System.Text.UTF8Encoding.Default
        'sGetValu2e.RequestEncoding = System.Text.Encoding.Default
        '  sGetValu2e.UserAgent = "Mozilla/4.0"
        Try
            '   sGetValu2e.Url = "http://ec.europa.eu/taxation_customs/dds2/eos/validation/services/validation?wsdl"
            Dim result As eoriValidationResult = sGetValu2e.validateEORI({KUNDE.EORITIN})

            If False Then

                Dim CallWebService As New EORI.validation
                '(Substitute the names of your own Server and Web 
                ' service for ServerName.WebServiceName above.) 
                ' CallWebService.validateEORI = txtEori
                ' Dim eori As New UID.eu.europa.ec.eoriResponse
                Dim arrEori As String() = {KUNDE.EORITIN}
                CallWebService.Timeout = 32768
                ' CallWebService.SoapVersion
                'MsgBox(CallWebService.validateEORI(arrEori))
                'CallWebService.validateEORIAsync(arrEori)
                'CallWebService.UserAgent = "MSIE 6.0"

                Dim sGetValue As EORI.eoriValidationResult = CallWebService.validateEORI(arrEori)
                Dim f As EORI.eoriResponse
                MsgBox(sGetValue.requestDate)
                MsgBox(sGetValue.errorDescription.ToString)

                MsgBox("OK")
                MsgBox(sGetValue.result)


                If f.status = 100 Then
                    sender.BackgroundImage = My.Resources.ok
                    'Button4.Visible = True
                    Exit Sub
                End If

            End If

        Catch ex2 As InvalidOperationException
            'Server.GetLastError()
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex2.Message, ex2.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
        Catch ex As Exception
            'Server.GetLastError()
            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)

        End Try
        sender.BackgroundImage = My.Resources.del

        Exit Sub
        Dim vat As New SDL.EORI.validation

        ' Dim EU3t As New SDL.eu.europa.ec.checkVatService("checkVatPort", "http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl") '"urn:ec.europa.eu:taxud:vies:services:checkVat:types")
        '   Dim EU4 As New EU_Uid_Pruefung.checkVatPortTyp
        ' EU3.checkVatPortType()
        '  "EU_Uid_Pruefung.checkVatPortType" 



        '   Dim ass As New EU_UID_Pruefung.checkVatPortTypeClient()

        '  ass.checkVatPortTypeClient()

        ' Dim s = EU3t.checkVat("AT", "U53187000", valid, name, adress)
        Dim str(1) As String  ' = {KUNDE.EORITIN}
        str(0) = "DE22372020005"
        '  MsgBox("")
        Dim s As EORI.eoriValidationResult = vat.validateEORI(str)
        MsgBox(s.result(0))
        Dim v As New EORI.validation()

        'Dim resp As eu.europa.ec1.eoriResponse
        'resp



        ' FINANZONLINE:::::::::::::::::::::::::::
        '_________________________________
        '  frmUidLink.link = uidlink
        '   frmUidLink.Show()

        '_________________________________
        Me.Cursor = Cursors.WaitCursor
        If cFinanzOnlineWebService.Call_Web_Service_MethodUID_Login() = 0 Then
            MsgBox("HURRA")
        End If

        '  If session <> "" Then
        '  Dim s As String
        '  Try
        's = Call_Web_Service_MethodUID_Abfrage(session)
        ' Call_Web_Service_MethodUID_Logout(session)
        ' uid_message = getmessage(s)
        ' If s = "0" Then
        'uid_message_report = "Die UID-Nummer " & txtUid.Text & " wurde geprüft und ist gültig."
        ' ElseIf s = "4" Then
        '  uid_message_report = "Die UID-Nummer " & txtUid.Text & " wurde geprüft und ist NICHT gültig."
        '  Else
        'uid_message_report = "Probleme bei der Abfrage - UID-Nummer: " & txtUid.Text
        '  End If
        '
        ' Catch ex As Exception
        '    MsgBox("Fehler beim Prüfen der UID-Nummer" & vbNewLine & vbNewLine & ex.Message) : End Try
        ' End If
        '  Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel2_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles lblFwlFiskal.LinkClicked
        showForm(firmenwortlautFiskal, "Firmenwortlaut - Fiskal")
    End Sub



    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        Me.Cursor = Cursors.WaitCursor
        printUID("AT", "U53187000", ADRESSE.UstIdKz, ADRESSE.UstIdNr)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Me.Cursor = Cursors.WaitCursor
        printEORI(KUNDE.EORITIN)
        Me.Cursor = Cursors.Default
    End Sub

    Sub printUID(uidKz_antragsteller, uid_antragsteller, uidKz, uid)
        If uidKz Is Nothing Then Exit Sub
        If uid Is Nothing Then Exit Sub
        If uidKz = "" Then Exit Sub
        If uid = "" Then Exit Sub
        printURL("http://ec.europa.eu/taxation_customs/vies/vatResponse.html?memberStateCode=" & uidKz & "&number=" & uid & "&requesterMemberStateCode=" & uidKz_antragsteller & "&requesterNumber=" & uid_antragsteller)
    End Sub

    Sub pdfUID(uidKz_antragsteller, uid_antragsteller, uidKz, uid)
        If uidKz Is Nothing Then Exit Sub
        If uid Is Nothing Then Exit Sub
        If uidKz = "" Then Exit Sub
        If uid = "" Then Exit Sub

        Dim url = SDL.cFinanzOnlineWebService.genUID_FormularWithoutSaving(uidKz + uid)

        'Dim url = "http://ec.europa.eu/taxation_customs/vies/vatResponse.html?memberStateCode=" & uidKz & "&number=" & uid & "&requesterMemberStateCode=" & uidKz_antragsteller & "&requesterNumber=" & uid_antragsteller ' alte SOAP-Abfrage!!!
        If url <> "" Then
            Dim pdf = VERAG_PROG_ALLGEMEIN.cFormularManager.getPDFViaSpirePDF_FromURL(url)
            'If pdf <> "" Then Process.Start(pdf)
        End If

    End Sub

    Sub printEORI(eoriNr, Optional pdfPath = "")
        timer_EORI.Interval = 2000
        If eoriNr Is Nothing Then Exit Sub
        eoriNr = eoriNr.Replace(" ", "").Trim
        '   printURL("http://ec.europa.eu/taxation_customs/dds2/eos/eori_validation.jsp?Lang=de&EoriNumb=" & eoriNr & "&Expand=true")

        Dim f As New frmInfo
        f.Controls.Clear()
        Dim WebBrowser As New VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx
        WebBrowser.ScriptErrorsSuppressed = True
        f.Controls.Add(WebBrowser)
        f.Visible = False
        f.WindowState = FormWindowState.Minimized
        f.Show()
        f_EORI = f
        f_EORI_PDF = pdfPath


        WebBrowser.Dock = DockStyle.Fill
        WebBrowser.Navigate(New Uri("http://ec.europa.eu/taxation_customs/dds2/eos/eori_validation.jsp?Lang=de&EoriNumb=" & eoriNr & "&Expand=true"))
        AddHandler WebBrowser.DocumentCompleted, Sub()
                                                     ' Print the document now that it is fully loaded.
                                                     If WebBrowser.ReadyState = WebBrowserReadyState.Complete Then
                                                         '   System.Threading.Thread.Sleep(1000)
                                                         '   WebBrowser.Print()
                                                         ' Dispose the WebBrowser now that the task is complete. 
                                                         ' WebBrowser.Dispose()
                                                         timer_EORI.Enabled = True
                                                     End If

                                                 End Sub


    End Sub

    Sub printURL(url)
        Dim WebBrowser As New VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx
        WebBrowser.ScriptErrorsSuppressed = True
        WebBrowser.Navigate(New Uri(url))
        WebBrowser.AllowNavigation = True
        'WebBrowser.Print()
        AddHandler WebBrowser.DocumentCompleted, Sub()
                                                     ' Print the document now that it is fully loaded.
                                                     System.Threading.Thread.Sleep(1000)
                                                     WebBrowser.Print()
                                                     ' Dispose the WebBrowser now that the task is complete. 
                                                     WebBrowser.Dispose()
                                                 End Sub

    End Sub


    Private Sub tbWeitereKundenDetails_SelectedIndexChanged(sender As Object, e As EventArgs) Handles tbWeitereKundenDetails.SelectedIndexChanged
        cboFirmaFMZOLL.Visible = (tbWeitereKundenDetails.SelectedIndex > 0)
        Label30.Visible = (tbWeitereKundenDetails.SelectedIndex > 0)
        btnExcel.Visible = (tbWeitereKundenDetails.SelectedTab Is tbOffenePosten)

        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("OP_LADEN", "SDL") Then
            btnReloadOP.Visible = (tbWeitereKundenDetails.SelectedTab Is tbOffenePosten)
        End If

    End Sub

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

        Dim f1 As New frmBonitaet(kdNr)
        f1.ShowDialog(Me)

        setKD(kdNr) 'aktualisieren
        Exit Sub


        Dim f As New frmFormulare(kdNr)
        f.Show()
        f.addForm("Boniteatsauskunft")

        Exit Sub
        If kdNr <= 0 Then Exit Sub
        Dim frmBonitaetBearbeiten As New frmBonitaetBearbeiten
        If frmBonitaetBearbeiten.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
            SQL.doSQL("UPDATE Kunden SET Bonität='" & frmBonitaetBearbeiten.lblBonitaet.Text & "', Bonitätsdatum='" & frmBonitaetBearbeiten.lblBonitaetsdatum._value & "' WHERE KundenNr=" & kdNr, "FMZOLL")
            setKD(kdNr)
        End If
    End Sub

    Private Sub FlatButton5_Click_1(sender As Object, e As EventArgs) Handles btnSaveOfferte.Click
        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG("OFFERTEN_SPERRE", "SDL") > 0 Then
            Exit Sub
        End If
        If dgvOffertenSperrliste.SelectedRows.Count > 0 Then
            SQL.doSQL("UPDATE Offerten SET Gesperrt=" & CInt(cbxSperreSetzen.Checked) & ", Gesperrt_Datum=GETDATE(), Gesperrt_Grund='" & txtSperreGrund.Text & "' WHERE KundenNr=" & kdNr & " AND OffertenNr=" & dgvOffertenSperrliste.SelectedRows(0).Cells("OffertenNr").Value & "", "FMZOLL")
        End If
    End Sub

    Private Sub cbxSperreSetzen_CheckedChanged(sender As Object, e As EventArgs) Handles cbxSperreSetzen.Click
        txtSperreDat.Text = Now.ToShortDateString & " " & Now.ToShortTimeString
    End Sub


    Private Sub cbxSperreSetzen_CheckedChanged_1(sender As Object, e As EventArgs) Handles cbxSperreSetzen.CheckedChanged
        cbxSperreSetzen.ForeColor = If(cbxSperreSetzen.Checked, Color.Red, Color.Black)
    End Sub



    Private Sub FlatButton6_Click(sender As Object, e As EventArgs) Handles FlatButton6.Click
        Dim f As New frmBonitätsverlauf(kdNr)
        f.Show()
        AddHandler f.FormClosed, Sub()
                                     setKD(kdNr)
                                 End Sub
    End Sub



    Private Sub btnExcel_Click(sender As Object, e As EventArgs) Handles btnExcel.Click
        Me.Cursor = Cursors.WaitCursor
        cProgramFunctions.genExcelFromDGV_NEW(dgvOffenePosten, False)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub LinkLabel1_LinkClicked_1(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        If trennungBesonderheiten Then
            rtbAbf_Besonderheiten.Text = checkNullStr(KUNDE.Besonderheiten)
        Else
            rtbAbf_Besonderheiten.Text = checkNullStr(KUNDE.Besonderheiten).Replace(" / ", vbNewLine)
        End If
        trennungBesonderheiten = Not trennungBesonderheiten
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        rtbAbf_Besonderheiten.ZoomFactor += 0.2
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        rtbAbf_Besonderheiten.ZoomFactor -= 0.2
    End Sub

    Private Sub btnPunkt2Save_Click(sender As Object, e As EventArgs) Handles btnPunkt2Save.Click
        SQL.doSQL("UPDATE Kunden SET Besonderheiten='" & rtbAbf_Besonderheiten.Text & "', [Sachbearbeiter] = '" & VERAG_PROG_ALLGEMEIN.cAllgemein.USRKURZNAME & "', [Geändert am] ='" & Now & "' WHERE KundenNr=" & kdNr, "FMZOLL")
        setKD(kdNr)
    End Sub

    Private Sub FlatButton7_Click(sender As Object, e As EventArgs) Handles btnVeragAnspr.Click
        Dim f As New frmKundeAnsprechpartnerTeams(KUNDE, KUNDE_ERW)
        If f.ShowDialog(Me) = DialogResult.OK Then
            setKD(kdNr)
        End If




        'Dim f As New frmKundeTeamZuordnung(KUNDE_ERW.kde_qsTeamId, KUNDE_ERW.kde_qsTeamMAId)

        'If f.ShowDialog(Me) = Windows.Forms.DialogResult.OK Then
        '    If f.SEL_TEAM IsNot Nothing Then
        '        KUNDE_ERW.kde_qsTeamId = f.SEL_TEAM.qstm_Id
        '        KUNDE_ERW.kde_qsTeamMAId = f.SEL_TEAM.qstm_Id
        '        KUNDE_ERW.kde_qsTeamId = If(f.SEL_MA Is Nothing, Nothing, f.SEL_MA.qtma_MaId)
        '        KUNDE_ERW.kde_qsTeamMAName = If(f.SEL_MA Is Nothing, Nothing, f.SEL_MA.qtma_name)
        '        KUNDE_ERW.kde_qsTeamName = f.SEL_TEAM.qstm_bezeichnung
        '        KUNDE_ERW.SAVE()
        '        '   SQL.doSQL("UPDATE tblKundenErweitert SET kde_qsTeamId='" & f.SEL_TEAM.qstm_Id & "', [kde_qsTeamMAId] = " & If(f.SEL_MA Is Nothing, "null", "'" & f.SEL_MA.qtma_MaId & "'") & " , [kde_qsTeamMAName] = " & If(f.SEL_MA Is Nothing, "null", "'" & f.SEL_MA.qtma_name & "'") & " , [kde_qsTeamName] = '" & f.SEL_TEAM.qstm_bezeichnung & "' WHERE kde_KundenNr=" & kdNr, "FMZOLL")
        '    Else
        '        KUNDE_ERW.kde_qsTeamId = Nothing
        '        KUNDE_ERW.kde_qsTeamMAId = Nothing
        '        KUNDE_ERW.kde_qsTeamId = Nothing
        '        KUNDE_ERW.kde_qsTeamMAName = Nothing
        '        KUNDE_ERW.kde_qsTeamName = Nothing
        '        KUNDE_ERW.SAVE()
        '        '  SQL.doSQL("UPDATE tblKundenErweitert SET kde_qsTeamId=null, [kde_qsTeamMAId] = null, [kde_qsTeamMAName] =null , [kde_qsTeamName] =null WHERE kde_KundenNr=" & kdNr, "FMZOLL")
        '    End If
        '    setKD(kdNr)
        'End If
    End Sub


    Private Sub cbxKdAuftragsNr_CheckedChanged(sender As Object, e As EventArgs) Handles cbxKdAuftragsNr.CheckedChanged
        txtFixeKdAtrNr.Enabled = cbxKdAuftragsNr.Checked
        txtInfoKdAtrNr.Enabled = cbxKdAuftragsNr.Checked
    End Sub

    Private Sub timer_EORI_Tick(sender As Object, e As EventArgs) Handles timer_EORI.Tick
        Try
            If f_EORI_PDF <> "" Then
                ' DirectCast(f_EORI.Controls(0), VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx).ShowSaveAsDialog()
                'DirectCast(f_EORI.Controls(0), VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx).


                'Dim urlPDF = DirectCast(f_EORI.Controls(0), VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx).Url.AbsoluteUri
                'MsgBox(urlPDF)
                'Dim pdf = VERAG_PROG_ALLGEMEIN.cFormularManager.getPDFViaSpirePDF_FromURL(urlPDF, "C:\Users\DEVELOPER1\Desktop\test.pdf")
                'If pdf <> "" Then Process.Start(pdf)

            Else
                DirectCast(f_EORI.Controls(0), VERAG_PROG_ALLGEMEIN.Kleinma.Controls.WebBrowserEx).Print()
            End If



            f_EORI.Close()


        Catch ex As Exception

        End Try

        timer_EORI.Enabled = False
    End Sub

    Private Sub tbKontakt_TabIndexChanged(sender As Object, e As EventArgs) Handles tbKontakt.SelectedIndexChanged
        If tbKontakt.SelectedTab Is tbKontaktSpez Then
            initKdKontakSpeziell()
        End If
    End Sub

    Sub initKdKontakSpeziell()
        'TabPage11.Controls.Clear() 
        ucKundenKontakte.init(kdNr)
    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
        If (txtT1VerzollungsadresseBestimmungszollstelle._value <> "" Or cbxGG.Checked) And txtGGDatum._value <> "" Then
            Dim GG As New VERAG_PROG_ALLGEMEIN.cGestellungsgarantien
            If Button9.Visible Then
                If dgvGestGarantie.SelectedRows.Count = 1 Then
                    GG = New VERAG_PROG_ALLGEMEIN.cGestellungsgarantien(dgvGestGarantie.SelectedRows(0).Cells("gg_id").Value)
                Else
                    Exit Sub
                End If
            End If
            GG.gg_KundenNr = kdNr
            GG.gg_erhalten_Datum = txtGGDatum._value
            GG.gg_Zollamt = If(cbxGG.Checked, "GENERELL", txtT1VerzollungsadresseBestimmungszollstelle._value)

            If Not Button9.Visible AndAlso VERAG_PROG_ALLGEMEIN.cGestellungsgarantien.ENTRY_Exists(kdNr, GG.gg_Zollamt, txtGGDatum._value) Then
                MsgBox("Der Eintrag existiert bereits!")
                Exit Sub
            End If

            GG.gg_Info = txtT1VerzollungsadresseBestimmungszollstelle.GET_VALUE_OnlyReturn(txtT1VerzollungsadresseBestimmungszollstelle._value, False)
            If GG.SAVE Then
                txtT1VerzollungsadresseBestimmungszollstelle.SET_VALUE("")
                setKD(kdNr)
                txtT1VerzollungsadresseBestimmungszollstelle.Focus()
            End If
            clearGG()
        End If
    End Sub

    Private Sub txtT1VerzollungsadresseBestimmungszollstelle_KeyDown(sender As Object, e As KeyEventArgs) Handles txtT1VerzollungsadresseBestimmungszollstelle.KeyDown, txtGGDatum.KeyDown
        If e.KeyCode = Keys.Return Then
            If txtT1VerzollungsadresseBestimmungszollstelle.usrcntl.Visible Then Exit Sub
            Button8.PerformClick()
        End If
    End Sub

    Private Sub dgvGestGarantie_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvGestGarantie.CellMouseClick
        If e.RowIndex < 0 Then Exit Sub
        DirectCast(sender, DataGridView).Rows(e.RowIndex).Selected = True
        If e.Button = Windows.Forms.MouseButtons.Right Then
            If dgvGestGarantie.SelectedRows.Count > 0 Then
                ContextMenuStrip3.Show(Cursor.Position)
            End If
        End If
    End Sub
    Private Sub dgvVertraege_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvVertraege.CellMouseClick
        If e.RowIndex < 0 Then Exit Sub
        DirectCast(sender, DataGridView).Rows(e.RowIndex).Selected = True
        If e.Button = Windows.Forms.MouseButtons.Right Then
            If dgvVertraege.SelectedRows.Count > 0 Then
                ContextMenuStrip4.Show(Cursor.Position)
            End If
        End If
    End Sub

    Private Sub ToolStripMenuItem3_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem3.Click
        If dgvGestGarantie.SelectedRows.Count > 0 Then
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kundendaten_bearbeiten", "SDL") Then
                If vbYes = MsgBox("Möchten Sie den Eintrag wirklich löschen?", vbYesNoCancel) Then
                    Dim GG As New VERAG_PROG_ALLGEMEIN.cGestellungsgarantien(dgvGestGarantie.SelectedRows(0).Cells("gg_id").Value)
                    If GG.DELETE() Then
                        setKD(kdNr)
                    End If
                End If
            End If
        End If
    End Sub


    Private Sub FlatButton8_Click(sender As Object, e As EventArgs) Handles btnThereforeTarifNr.Click
        cProgramFunctions.openThereforeNavigatorTarifnummern(kdNr)
    End Sub

    Private Sub FlatButton7_Click_1(sender As Object, e As EventArgs) Handles btnThereforeKundeninfo.Click
        cProgramFunctions.openThereforeNavigatorKudnenInfo(kdNr)
    End Sub

    Private Sub timerOP_Tick(sender As Object, e As EventArgs) Handles timerOP.Tick
        Dim sumGes As Double = 0
        timerOP.Enabled = False
        For cnt = dgvOffenePosten.Rows.Count - 1 To 0 Step -1
            Dim r As DataGridViewRow = dgvOffenePosten.Rows(cnt)
            sumGes += CDbl(r.Cells("Betrag").Value)
            r.Cells("clmnSaldo").Value = sumGes
        Next
    End Sub

    Private Sub ScannenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ScannenToolStripMenuItem.Click
        If dgvGestGarantie.SelectedRows.Count = 1 Then
            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "GESTELLUNGS_GARANTIEN", "", "", "", "GG_" & dgvGestGarantie.SelectedRows(0).Cells("gg_Zollamt").Value, kdNr)
            Dim frmScan As New VERAG_PROG_ALLGEMEIN.frmScan("DirectScan")
            frmScan.DefaultFileName = DS.da_name

            If frmScan.ShowDialog(Me) = DialogResult.OK Then
                If frmScan.ReturnValue IsNot Nothing Then
                    Dim Filename = DS.da_name
                    If frmScan.fileName <> "" Then Filename = frmScan.fileName
                    If DS.uploadDataToDATENSERVER_fromBytes(frmScan.ReturnValue, Filename, ".pdf") Then
                        Dim GG As New VERAG_PROG_ALLGEMEIN.cGestellungsgarantien(dgvGestGarantie.SelectedRows(0).Cells("gg_id").Value)
                        GG.gg_datenarchivId = DS.da_id
                        GG.SAVE()
                        initDGVGestGarantie()
                    End If
                End If
            End If

        End If
    End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click

        clearGG()

    End Sub

    Sub clearGG()
        txtT1VerzollungsadresseBestimmungszollstelle.SET_VALUE("")
        txtGGDatum.Text = ""
        cbxGG.Checked = False
        Button8.Text = "Hinzufügen"
        Button9.Visible = False
    End Sub


    Sub clearKV()
        cboVertrag.changeItem("")
        datVertrag.Text = ""
        txtVertragVermerk.Text = ""
        Button11.Text = "Hinzufügen"
        Button12.Visible = False
    End Sub

    Private Sub PDFLöschenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles PDFLöschenToolStripMenuItem.Click
        If dgvGestGarantie.SelectedRows.Count = 1 Then
            If vbYes = MsgBox("Möchten Sie das PDF wirklich löschen?", vbYesNoCancel) Then

                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "GESTELLUNGS_GARANTIEN", "", "", "", "GG_" & dgvGestGarantie.SelectedRows(0).Cells("gg_Zollamt").Value, kdNr)
                DS.DELETE_COMPLETE()

                Dim GG As New VERAG_PROG_ALLGEMEIN.cGestellungsgarantien(dgvGestGarantie.SelectedRows(0).Cells("gg_id").Value)
                GG.gg_datenarchivId = Nothing
                GG.SAVE()

                initDGVGestGarantie()
            End If
        End If
    End Sub

    Private Sub ÄndernToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ÄndernToolStripMenuItem.Click
        If dgvGestGarantie.SelectedRows.Count = 1 Then
            Dim GG As New VERAG_PROG_ALLGEMEIN.cGestellungsgarantien(dgvGestGarantie.SelectedRows(0).Cells("gg_id").Value)

            txtT1VerzollungsadresseBestimmungszollstelle.SET_VALUE(GG.gg_Zollamt)
            txtGGDatum.Text = GG.gg_erhalten_Datum
            cbxGG.Checked = (GG.gg_Zollamt = "GENERELL")
            Button8.Text = "Ändern"
            Button9.Visible = True

        End If
    End Sub

    Private Sub HochladenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles HochladenToolStripMenuItem.Click
        If dgvGestGarantie.SelectedRows.Count = 1 Then
            Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "GESTELLUNGS_GARANTIEN", "", "", "", "GG_" & dgvGestGarantie.SelectedRows(0).Cells("gg_Zollamt").Value, kdNr)
            If DS.uploadDataToDATENSERVERFileDialog(, ".pdf", , "PDF") Then
                Dim gg As New VERAG_PROG_ALLGEMEIN.cGestellungsgarantien(dgvGestGarantie.SelectedRows(0).Cells("gg_id").Value)
                gg.gg_datenarchivId = DS.da_id
                gg.SAVE()
                initDGVGestGarantie()
            End If
        End If
    End Sub

    Private Sub KopierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles KopierenToolStripMenuItem.Click
        Clipboard.SetText(rtbAbf_Besonderheiten.SelectedText)
    End Sub

    Private Sub ToolStripMenuItem2_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem2.Click
        If dgvAufschub.SelectedRows.Count > 0 Then
            Clipboard.SetText(dgvAufschub.SelectedRows(0).Cells("HZA").Value & dgvAufschub.SelectedRows(0).Cells("KontoNr").Value)
        End If
    End Sub

    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click
        Me.Cursor = Cursors.WaitCursor
        pdfUID("AT", "U53187000", ADRESSE.UstIdKz, ADRESSE.UstIdNr)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Me.Cursor = Cursors.WaitCursor
        'printEORI(KUNDE.EORITIN, "C:\Users\DEVELOPER1\Desktop\test.pdf")

        'Dim url = "https://ec.europa.eu/taxation_customs/dds2/eos/eori_validation.jsp?Lang=de&EoriNumb=" & KUNDE.EORITIN & "&Expand=true"

        Dim EORI_NR = KUNDE.EORITIN.ToString()

        EORI_NR.Replace("-", "").Replace(" ", "").Trim

        If EORI_NR = "" Then Me.Cursor = Cursors.Default : Exit Sub

        Dim url = SDL.cEORIWebService.genEORI_Formular(EORI_NR)

        Dim pdf = VERAG_PROG_ALLGEMEIN.cFormularManager.getPDFViaSpirePDF_FromURL(url)
        'If pdf <> "" Then Process.Start(pdf)


        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
        If cboVertrag._value <> "" And datVertrag._value <> "" Then
            Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege
            If Button12.Visible Then
                If dgvVertraege.SelectedRows.Count = 1 Then
                    KV = New VERAG_PROG_ALLGEMEIN.cKundenVertraege(dgvVertraege.SelectedRows(0).Cells("kv_id").Value)
                Else
                    Exit Sub
                End If
            End If
            KV.kv_KundenNr = kdNr
            KV.kv_erhalten_Datum = datVertrag._value
            'KV.kv_Zollamt = If(cbxKV.Checked, "GENERELL", txtT1VerzollungsadresseBestimmungszollstelle._value)

            'If Not Button9.Visible AndAlso VERAG_PROG_ALLGEMEIN.cKundenVertraege.ENTRY_Exists(kdNr, KV.kv_Zollamt) Then
            '    MsgBox("Der Eintrag existiert bereits!")
            '    Exit Sub
            'End If

            KV.kv_vertragArtId = cboVertrag._value
            KV.kv_Info = txtVertragVermerk.Text

            If KV.SAVE Then
                setKD(kdNr)
            End If
            clearKV()
        End If
    End Sub


    Private Sub Button12_Click(sender As Object, e As EventArgs) Handles Button12.Click
        clearKV()
    End Sub

    Private Sub ToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem1.Click
        If dgvVertraege.SelectedRows.Count > 0 Then
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kundendaten_bearbeiten", "SDL") Then
                If vbYes = MsgBox("Möchten Sie den Vertrag wirklich löschen?", vbYesNoCancel) Then
                    Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(dgvVertraege.SelectedRows(0).Cells("kv_id").Value)
                    If KV.DELETE() Then
                        setKD(kdNr)
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub ToolStripMenuItem4_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem4.Click
        If dgvVertraege.SelectedRows.Count = 1 Then
            Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(dgvVertraege.SelectedRows(0).Cells("kv_id").Value)

            cboVertrag.changeItem(KV.kv_vertragArtId)
            datVertrag.Text = KV.kv_erhalten_Datum
            txtVertragVermerk.Text = KV.kv_Info

            Button11.Text = "Ändern"
            Button12.Visible = True

        End If
    End Sub

    Private Sub ToolStripMenuItem5_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem5.Click
        If dgvVertraege.SelectedRows.Count = 1 Then
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kundendaten_bearbeiten", "SDL") Then
                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "KD_VERTRÄGE", "", "", "", "KV_" & dgvVertraege.SelectedRows(0).Cells("kv_id").Value, kdNr)
                If DS.uploadDataToDATENSERVERFileDialog(, ".pdf", , "PDF") Then
                    Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(dgvVertraege.SelectedRows(0).Cells("kv_id").Value)
                    KV.kv_datenarchivId = DS.da_id
                    KV.SAVE()
                    initDGVVertraege()
                End If
            End If
        End If
    End Sub

    Private Sub ToolStripMenuItem6_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem6.Click
        If dgvVertraege.SelectedRows.Count = 1 Then
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kundendaten_bearbeiten", "SDL") Then
                Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "KD_VERTRÄGE", "", "", "", "KV_" & dgvVertraege.SelectedRows(0).Cells("kv_id").Value, kdNr)
                Dim frmScan As New VERAG_PROG_ALLGEMEIN.frmScan("DirectScan")
                frmScan.DefaultFileName = DS.da_name

                If frmScan.ShowDialog(Me) = DialogResult.OK Then
                    If frmScan.ReturnValue IsNot Nothing Then
                        Dim Filename = DS.da_name
                        If frmScan.fileName <> "" Then Filename = frmScan.fileName
                        If DS.uploadDataToDATENSERVER_fromBytes(frmScan.ReturnValue, Filename, ".pdf") Then
                            Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(dgvVertraege.SelectedRows(0).Cells("kv_id").Value)
                            KV.kv_datenarchivId = DS.da_id
                            KV.SAVE()
                            initDGVVertraege()
                        End If
                    End If
                End If
            End If

        End If
    End Sub

    Private Sub ToolStripMenuItem7_Click(sender As Object, e As EventArgs) Handles ToolStripMenuItem7.Click
        If dgvVertraege.SelectedRows.Count = 1 Then
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kundendaten_bearbeiten", "SDL") Then
                If vbYes = MsgBox("Möchten Sie das PDF wirklich löschen?", vbYesNoCancel) Then

                    Dim DS As New VERAG_PROG_ALLGEMEIN.cDATENSERVER("DOKUMENTE", "KD_VERTRÄGE", "", "", "", "KV_" & dgvVertraege.SelectedRows(0).Cells("kv_id").Value, kdNr)
                    DS.DELETE_COMPLETE()

                    Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(dgvVertraege.SelectedRows(0).Cells("kv_id").Value)
                    KV.kv_datenarchivId = Nothing
                    KV.SAVE()
                    initDGVVertraege()
                End If
            End If
        End If
    End Sub

    Private Sub GültigungültigToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles GültigungültigToolStripMenuItem.Click
        If dgvVertraege.SelectedRows.Count = 1 Then
            If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("Kundendaten_bearbeiten", "SDL") Then
                Dim KV As New VERAG_PROG_ALLGEMEIN.cKundenVertraege(dgvVertraege.SelectedRows(0).Cells("kv_id").Value)
                KV.kv_gueltig = Not KV.kv_gueltig
                KV.SAVE()
                initDGVVertraege()
            End If
        End If
    End Sub

    Private Sub Button13_Click(sender As Object, e As EventArgs) Handles Button13.Click
        genUIDEORIList(kdNr, "UID")

    End Sub

    Sub genUIDEORIList(kdNr, typeListe)
        If kdNr <= 0 Then Exit Sub
        Dim frmList As New frmKundenUIDEORI_List
        Select Case typeListe
            Case "UID"
                Dim dt = SQL.loadDgvBySql("SELECT [uid_id],[uid_KundenNr] KundenNr,[uid_UstIdKz]UstIdKz,[uid_UstIdNr]UstIdNr,[uid_Datum]Datum,[uid_valid]Gültig,[uid_Sachbearbeiter]Sachbearbeiter,[uid_stufe]Stufe FROM [tblUIDPruefung]where uid_KundenNr='" & kdNr & "' ORDER BY uid_Datum desc", "FMZOLL")
                If dt IsNot Nothing Then
                    frmList.dgv.DataSource = dt
                    frmList.dgv.Columns("uid_id").Visible = False
                    AddHandler frmList.dgv.CellDoubleClick, Sub()
                                                                Dim PdfTmp = SDL.FormularManagerNEU.UID_PRUEFUNG_PROTOKOLL(frmList.dgv.SelectedRows(0).Cells("uid_id").Value)
                                                                If PdfTmp <> "" Then
                                                                    Process.Start(PdfTmp)

                                                                End If
                                                            End Sub
                    frmList.Show(Me)
                End If
            Case "EORI"
        End Select


    End Sub

    Private Sub Button15_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

    Private Sub dgvVollmachten_CellContentClick_1(sender As Object, e As DataGridViewCellEventArgs) Handles dgvVollmachten.CellContentClick

    End Sub

    Private Sub dgvVollmachten_DragDrop(sender As Object, e As DragEventArgs) Handles dgvVollmachten.DragDrop
        Try
            If e.Data.GetDataPresent("FileDrop", True) = True Then
                Dim FileList As String() = CType(e.Data.GetData("FileDrop"), Object) 'Hier wird der Variable "Wert" das übergeben, was wir auf die Form gezogen haben. Bei einer Datei wäre es dann der Pfad der Datei.
                If FileList.Count > 0 Then
                    'If Not _MULTI_FILES And FileList.Count > 1 Then
                    '    MsgBox("Es können nicht mehrere Dateien hochgeladen werden!")
                    '    Exit Sub
                    'End If
                    For Each W In FileList
                        If Not W.ToUpper.EndsWith(".EXE") Then
                            Dim datum = IIf(dgvVollmachten.Rows(tmprowindex).Cells("kdvm_erhalten_Datum").Value Is DBNull.Value, Now, dgvVollmachten.Rows(tmprowindex).Cells("kdvm_erhalten_Datum").Value)
                            Dim l As New frmKundenZOLLVollmachten(kdNr, -1, W)
                            If l.ShowDialog(frmGrayOut) = DialogResult.OK Then
                                initDGVVollmachten()
                            End If
                        End If
                    Next
                End If
            End If
        Catch ex As Exception
            MsgBox("   FEHLER: DragDrop!" & ex.Message & ex.StackTrace)
        End Try
    End Sub

    Private Sub Label17_Click(sender As Object, e As EventArgs) Handles Label17.Click

    End Sub

    Private Sub grpAbfertigung_Enter(sender As Object, e As EventArgs) Handles grpAbfertigung.Enter

    End Sub

    Private Sub Panel5_Paint(sender As Object, e As PaintEventArgs) Handles Panel5.Paint

    End Sub

    Private Sub Button15_Click_1(sender As Object, e As EventArgs) Handles btnVMhinzufuegen.Click
        Dim where = VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA

        Dim dt = SQL.loadDgvBySql("SELECT [kdvma_Id], [kdvma_Bezeichnung] FROM [tblKundenVollmachtenArt] where [kdvma_visible] = 1 AND [kdvma_Firma]='" & where & "'", "FMZOLL")

        cntxtAddVM.Items.Clear()
        For Each dr As DataRow In dt.Rows
            Dim i As New ToolStripMenuItem
            i.Text = dr.Item(1).ToString
            i.Name = "kdvma_id_" & dr.Item(0).ToString
            cntxtAddVM.Items.Add(i)
            AddHandler i.Click, AddressOf DToolStripMenuItem_Click
        Next
        btnVMhinzufuegen.ContextMenuStrip = cntxtAddVM
        Dim ptLowerLeft As New Point(sender.width, sender.Height)
        ptLowerLeft = sender.PointToScreen(ptLowerLeft)
        ptLowerLeft.X -= sender.width
        cntxtAddVM.Show(ptLowerLeft)

    End Sub

    Private Sub DToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DToolStripMenuItem.Click
        If sender.name.contains("kdvma_id_") Then
            Dim vmaText As String = sender.name.ToString.Replace("kdvma_id_", "")
            Dim vmaNr As Integer = Convert.ToInt32(vmaText)
            Dim l As New frmKundenZOLLVollmachten(kdNr, vmaNr)
            If l.ShowDialog(frmGrayOut) = DialogResult.OK Then

            End If
            initDGVVollmachten()
        End If

    End Sub

    Private Sub dgvVertraege_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvVertraege.CellContentClick

    End Sub
End Class
