Imports System.ComponentModel
Imports System.Resources
Imports System.Data.SqlClient
Imports System.Reflection
Imports Microsoft.Office.Interop

Public Class usrCntlKartenDaten
    Dim KUNDE As New cKunden
    Public kdNr As Integer
    Public kdNr_filter As Boolean = False
    Dim kundenSQL As New kundenSQL
    'Private bindingSDL As New BindingSource
    ' Private dataAdapterLKW As New SqlDataAdapter
    Dim SQL As New SQL
    'Dim table As New DataTable()
    Dim FUNC As New cProgramFunctions
    'Dim bindingString As String
    Dim aktbtn As String = ""
    Dim dgvInitWait As Boolean = False
    Dim aktSDLNr As Integer = -1
    Dim fullyPainted = False



    Protected Overrides Sub WndProc(ByRef m As Message)
        MyBase.WndProc(m)
        If m.Msg = 15 AndAlso Not fullyPainted Then
            fullyPainted = True

            SET_SDL(-1)

            '  initAllg()
            '  initFilter()
        End If
    End Sub


    Private Sub usrCntlKartenDaten_Layout(sender As Object, e As LayoutEventArgs) Handles Me.Layout

    End Sub
    ' Dim show200 = True
    Private Sub usrCntlDaten_Load(sender As Object, e As EventArgs) Handles Me.Load
        EnableDoubleBuffered(dgvSDL)
        '  MsgBox("L")
        ' Exit Sub
        ' Dim systemType As Type = dgvSDL.GetType()
        '  Dim propertyInfo As PropertyInfo = systemType.GetProperty("DoubleBuffered", BindingFlags.Instance Or BindingFlags.NonPublic)
        'propertyInfo.SetValue(dgvSDL, True, Nothing)

        init()

        AddHandler SplitContainer1.Panel1.Scroll, Sub()
                                                      initFilterLeft()
                                                  End Sub

        AddHandler cbxMax200Eintrage.Click, Sub()
                                                reClick()
                                            End Sub
        AddHandler cbxArchiv.Click, Sub()
                                        reClick()
                                    End Sub


    End Sub

    Public Shared Sub EnableDoubleBuffered(ByRef dgv As DataGridView)
        Dim dgvType As Type = dgv.[GetType]()
        Dim pi As PropertyInfo = dgvType.GetProperty("DoubleBuffered", BindingFlags.Instance Or BindingFlags.NonPublic)
        pi.SetValue(dgv, True, Nothing)
    End Sub


    Sub init()

        dgvInitWait = True

        Dim kdNr_WHERE = ""
        If kdNr_filter Then
            kdNr_WHERE = ""
        End If
        If kdNr_filter Then
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT KundenSDL.SDLNr FROM KundenSDL INNER JOIN [Speditionsdienstleistungen] as S ON s.SDLNr=KundenSDL.sdlnr WHERE s.SDLTypNr IN (1,2) AND KundenSDL.KundenNr = '" & kdNr & "'  group by KundenSDL.SDLNr ")
            If dt Is Nothing Then
                MsgBox("Es wurden noch keine Leistungen freigeschaltet.")
            Else
                btnSDL_IDS.Visible = dt.Select("SDLNr=100").Count > 0
                btnSDL_Woelfl.Visible = dt.Select("SDLNr=101").Count > 0
                btnSDL_UTA.Visible = dt.Select("SDLNr=212").Count > 0
                btnSDL_MautAT.Visible = dt.Select("SDLNr=200").Count > 0
                btnSDL_MautDE.Visible = dt.Select("SDLNr=201").Count > 0
                btnSDL_MautIT.Visible = dt.Select("SDLNr=202").Count > 0
                btnSDL_MautCZ.Visible = dt.Select("SDLNr=203").Count > 0
                btnSDL_Hugo.Visible = dt.Select("SDLNr=213").Count > 0
                btnSDL_PLOSE.Visible = dt.Select("SDLNr=214").Count > 0
                btnSDL_PLOSE_IT.Visible = dt.Select("SDLNr=215").Count > 0
                btnSDL_PLOSE_CZ.Visible = dt.Select("SDLNr=216").Count > 0
                btnMANAbgasplakette.Visible = dt.Select("SDLNr=500").Count > 0
                btnVERAGParkplatz.Visible = dt.Select("SDLNr=501").Count > 0

                btnSDL_MautPL.Visible = dt.Select("SDLNr=209").Count > 0
                btnSDL_MautSI.Visible = dt.Select("SDLNr=210").Count > 0
                btnSDL_MautMSE.Visible = dt.Select("SDLNr=208").Count > 0

                btnSDL_MotorWay.Visible = dt.Select("SDLNr=205").Count > 0
                btnSDL_ECOTAX.Visible = dt.Select("SDLNr=211").Count > 0
                btnSDL_FREJUS.Visible = dt.Select("SDLNr=207").Count > 0
                btnSDL_DouBox.Visible = dt.Select("SDLNr=206").Count > 0
            End If

            SplitContainer1.Panel2Collapsed = False
        Else

            Dim dt As DataTable = SQL.loadDgvBySql("SELECT SDLNr FROM   [Speditionsdienstleistungen]  WHERE SDLTypNr IN (1,2)   ")
            If dt IsNot Nothing Then
                btnSDL_IDS.Visible = dt.Select("SDLNr=100").Count > 0
                btnSDL_Woelfl.Visible = dt.Select("SDLNr=101").Count > 0
                btnSDL_UTA.Visible = dt.Select("SDLNr=212").Count > 0
                btnSDL_MautAT.Visible = dt.Select("SDLNr=200").Count > 0
                btnSDL_MautDE.Visible = dt.Select("SDLNr=201").Count > 0
                btnSDL_MautIT.Visible = dt.Select("SDLNr=202").Count > 0
                btnSDL_MautCZ.Visible = dt.Select("SDLNr=203").Count > 0
                btnSDL_Hugo.Visible = dt.Select("SDLNr=213").Count > 0
                btnSDL_PLOSE.Visible = dt.Select("SDLNr=214").Count > 0
                btnSDL_PLOSE_IT.Visible = dt.Select("SDLNr=215").Count > 0
                btnSDL_PLOSE_CZ.Visible = dt.Select("SDLNr=216").Count > 0
                btnMANAbgasplakette.Visible = dt.Select("SDLNr=500").Count > 0
                btnVERAGParkplatz.Visible = dt.Select("SDLNr=501").Count > 0

                btnSDL_MautPL.Visible = dt.Select("SDLNr=209").Count > 0
                btnSDL_MautSI.Visible = dt.Select("SDLNr=210").Count > 0
                btnSDL_MautMSE.Visible = dt.Select("SDLNr=208").Count > 0

                btnSDL_MotorWay.Visible = dt.Select("SDLNr=205").Count > 0
                btnSDL_ECOTAX.Visible = dt.Select("SDLNr=211").Count > 0
                btnSDL_FREJUS.Visible = dt.Select("SDLNr=207").Count > 0
                btnSDL_DouBox.Visible = dt.Select("SDLNr=206").Count > 0
            End If


            SplitContainer1.Panel2Collapsed = False
            dgvSDL_SelectionChanged(dgvSDL, New System.EventArgs)

        End If

        SET_SDL(-1)

        ' pnlFilter.Height = 0
        '   Me.dgvSDL.DataSource = Me.bindingSDL

        '  btnFilter.Left = Panel4.Width - btnFilter.Width
        'pnlFilter.AutoScroll = False




        dgvInitWait = False
        Panel3.Visible = True
        'btnSDL_Alle.PerformClick()
        'btnFilter.PerformClick()

    End Sub




    Sub initFilterLeft()
        Dim left_value As Integer = SplitContainer1.Panel1.HorizontalScroll.Value 'HorizontalScrollingOffset
        dgvFILTER.Left = (-1) * left_value
    End Sub

    

    Sub initFilter()
        dgvInitWait = True

        dgvFILTER.RowTemplate.Height = dgvFILTER.Height
        If Not fullyPainted Then Exit Sub ' nur wenn die usrcntl komplett gelden wurde...
        'pnlFilter.Controls.Clear()
        Try
            dgvFILTER.Columns.Clear()
        Catch ex As Exception

        End Try
        For Each c As DataGridViewColumn In dgvSDL.Columns
            Dim cNew As DataGridViewColumn = c.Clone

            If c.ReadOnly And c.Name = "IDS-KdNr" Then
                cNew = New DataGridViewTextBoxColumn
                cNew.Name = c.Name
                cNew.Width = c.Width
                cNew.Visible = c.Visible
                'KundenNr
            End If
            cNew.MinimumWidth = c.Width
            dgvFILTER.Columns.Add(cNew)
            If cNew.GetType Is GetType(DataGridViewCheckBoxColumn) Then
                DirectCast(cNew, DataGridViewCheckBoxColumn).ThreeState = True
                DirectCast(cNew, DataGridViewCheckBoxColumn).DefaultCellStyle.NullValue = CheckState.Indeterminate
            End If
        Next

        If dgvFILTER IsNot Nothing AndAlso dgvFILTER.ColumnCount > 0 Then

            'dgv.AllowUserToAddRows = False
            dgvFILTER.Rows.Add()
            '   pnlTest.Controls.Add(dgv)
            ' dgv.Top = 0
            ' dgv.Left = 0
            dgvFILTER.Width = dgvSDL.Width
        If kdNr_filter Then
            initKDFilter()
            End If
        End If

        dgvInitWait = False

    End Sub

    Dim txtchanged As Boolean = False
    Sub initSearchOLD()
        reClick()
        Exit Sub
        ' MsgBox("SEARCH")
        txtchanged = True
        ' initSDLBinding()
        initAllg()
        If kdNr_filter Then
            initKDFilter()
        End If

        dgvSDL.RELOAD()
        txtchanged = False
        dgvSDL.ClearSelection()
        If dgvSDL.RowCount > 0 Then dgvSDL.Rows(0).Cells(0).Selected = True
        'dgvSDL_SelectionChanged(dgvSDL, New EventArgs)
    End Sub

    Function getSqlText(t) As String
        Try
            Return t.Replace("'", "")
        Catch ex As Exception
            Return ""
        End Try
    End Function

    Function getFilter() As String


        Dim filter As String = ""
        Dim andstr As String = ""

        If dgvFILTER.RowCount > 0 Then
            For Each c As DataGridViewCell In dgvFILTER.Rows(0).Cells
                If c.Value IsNot DBNull.Value Then
                    If c.GetType Is GetType(DataGridViewTextBoxCell) Then
                        If c.Value IsNot Nothing AndAlso c.Value <> "" Then
                            Dim srchstr = getSqlText(c.Value.ToString.Trim)
                            If c.OwningColumn.Name.Contains("SDLNr") Then
                                filter &= andstr & " SDL.[" & c.OwningColumn.Name & "] LIKE '%" & srchstr & "%' "
                            ElseIf c.OwningColumn.Name.Contains("IDS-KdNr") Then
                                filter &= andstr & " (SELECT TOP 1 [CustomerCode] FROM [VERAG].[dbo].[tbl_IDS_Kunden]  WHERE [KdNrVERAG]=KundenNr AND KdNrAlt =0  ORDER BY Zeitstempel DESC)  LIKE '%" & srchstr & "%'  "
                                ElseIf IsDate(srchstr) Then
                                    If srchstr.ToLower = "ist null" Then
                                    filter &= andstr & "( [" & c.OwningColumn.Name & "] is null ) "
                                Else
                                    filter &= andstr & " convert(varchar,[" & c.OwningColumn.Name & "] ,104) LIKE '%" & srchstr & "%' "
                                End If
                            Else
                                If srchstr.ToLower = "ist null" Then
                                    filter &= andstr & "( [" & c.OwningColumn.Name & "] LIKE '' OR  [" & c.OwningColumn.Name & "] is null ) "
                                Else
                                    filter &= andstr & " [" & c.OwningColumn.Name & "] LIKE '%" & srchstr & "%' "
                                End If
                            End If
                            andstr = " AND "
                        End If
                    ElseIf c.GetType Is GetType(DataGridViewCheckBoxCell) Then
                        If c.Value IsNot Nothing AndAlso c.Value.ToString <> "" Then
                            If c.Value = CheckState.Checked Then
                                filter &= andstr & " SDL.[" & c.OwningColumn.Name & "] =1 "
                                andstr = " AND "
                            ElseIf c.Value = CheckState.Unchecked Then
                                filter &= andstr & " SDL.[" & c.OwningColumn.Name & "] =0 "
                                andstr = " AND "
                            End If
                        End If
                    End If

                End If
            Next
        End If

        Return filter
    End Function




    Sub clearFilter()
        If dgvFILTER.RowCount > 0 Then
            For Each c As DataGridViewCell In dgvFILTER.Rows(0).Cells
                c.Value = c.DefaultNewRowValue
            Next
        End If
        'initFilter()
        'If pnlFilterInside.HasChildren Then
        'pnlFilterInside.Controls.Clear()
        ' End If
    End Sub



    '  Sub setBindingstring(ByVal b As String)
    '      bindingString = b
    '  End Sub

    Sub initAllg()
        If Not fullyPainted Then Exit Sub ' nur wenn die usrcntl komplett gelden wurde...
        Try

            With dgvSDL
                .RowTemplate.Height = 20
                .AllowUserToOrderColumns = False
                .AllowUserToResizeRows = False
                .SelectionMode = DataGridViewSelectionMode.FullRowSelect

                '.AutoGenerateColumns = False '??HM:::b
                .Columns("Vermerk").MinimumWidth = 150
                .Columns("Erfassungsdatum").Visible = False
                If aktSDLNr <> 200 Then .Columns("Änderungsdatum").Visible = False
                If aktSDLNr <> 200 Then .Columns("Sachbearbeiter").Visible = False
                .Columns("SDLNr").Visible = False
                .Columns("History").Visible = False
                .ReadOnly = True
                If .Columns("Bestelldatum") IsNot Nothing Then .Columns("Bestelldatum").DefaultCellStyle.Format = "d"
                If .Columns("Lieferdatum") IsNot Nothing Then .Columns("Lieferdatum").DefaultCellStyle.Format = "d"
                '.Columns("KundenNr").Visible = False

                '  .Columns("SDLNr").Visible = False
                .Columns("SDLNr").Width = 50
                If aktSDLNr = -1 Then .Columns("SDLNr").Visible = True

                Try
                    .Columns("SDLBez").ReadOnly = True
                    .Columns("SDLBez").Width = 150
                Catch : End Try
                '   Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, 

                .Columns("Vermerk").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                .Columns("KfzKennzeichen").AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
                '.Columns("Vermerk").Width = 250

                If .Columns("Ersatzkarte") IsNot Nothing Then .Columns("Ersatzkarte").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter : .Columns("Ersatzkarte").HeaderText = "Ersatzk."
                If .Columns("Gesperrt") IsNot Nothing Then .Columns("Gesperrt").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter : .Columns("Gesperrt").HeaderText = "Gesp."
                If .Columns("Defekt") IsNot Nothing Then .Columns("Defekt").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter : .Columns("Defekt").HeaderText = "Def."
                If .Columns("Verloren") IsNot Nothing Then .Columns("Verloren").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter : .Columns("Verloren").HeaderText = "Verl."
                If .Columns("Gestohlen") IsNot Nothing Then .Columns("Gestohlen").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter : .Columns("Gestohlen").HeaderText = "Gest."
                If .Columns("Retourniert") IsNot Nothing Then .Columns("Retourniert").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter : .Columns("Retourniert").HeaderText = "Ret."
                If .Columns("TelepassErsatzkarte") IsNot Nothing Then .Columns("TelepassErsatzkarte").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter : .Columns("TelepassErsatzkarte").HeaderText = "Ers.TP"
                If .Columns("LKWAbgemeldet") IsNot Nothing Then .Columns("LKWAbgemeldet").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter : .Columns("LKWAbgemeldet").HeaderText = "Abgem."

                .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

                redRows()


            End With

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


    Sub initDGVWidth()
        Dim DGVwidth = 0
        Dim reduceWidth = 0
        For Each c As DataGridViewColumn In dgvSDL.Columns
            DGVwidth += c.Width
        Next
        Dim DGVheight = 0
        For Each r As DataGridViewRow In dgvSDL.Rows
            DGVheight += r.Height
        Next
        DGVheight += 50
        ' 

        If DGVheight > (SplitContainer1.Panel1.Height) Then
            dgvSDL.Height = DGVheight
            reduceWidth = 25 ' Scrollbar
        Else
            dgvSDL.Height = SplitContainer1.Panel1.Height - 25
        End If
        If DGVwidth > SplitContainer1.Panel1.Width Then
            dgvSDL.Width = DGVwidth - reduceWidth
        Else
            dgvSDL.Width = SplitContainer1.Panel1.Width - reduceWidth
        End If

    End Sub


    Sub redRows()
        With dgvSDL
            For Each r As DataGridViewRow In .Rows
                'If .Columns.Contains("Ersatzkarte") Then ifContainsAndTrueRed(r, "Ersatzkarte")
                If .Columns.Contains("Gesperrt") Then ifContainsAndTrueRed(r, "Gesperrt")
                If .Columns.Contains("Defekt") Then ifContainsAndTrueRed(r, "Defekt")
                If .Columns.Contains("Verloren") Then ifContainsAndTrueRed(r, "Verloren")
                If .Columns.Contains("Gestohlen") Then ifContainsAndTrueRed(r, "Gestohlen")
                If .Columns.Contains("Retourniert") Then ifContainsAndTrueRed(r, "Retourniert")
                '   If .Columns.Contains("TelepassErsatzkarte") Then ifContainsAndTrueRed(r, "TelepassErsatzkarte")
                If .Columns.Contains("LKWAbgemeldet") Then ifContainsAndTrueRed(r, "LKWAbgemeldet")
            Next
        End With
    End Sub
    Sub ifContainsAndTrueRed(r As DataGridViewRow, t As String)
        If r.Cells(t).Value IsNot DBNull.Value AndAlso r.Cells(t).Value = True Then
            r.DefaultCellStyle.ForeColor = Color.Red
        End If
    End Sub
    Sub initBtnClick(b As Button)
        'Dim defaufl_color As Color = Color.FromArgb(240, 245, 255)
        Dim defaufl_color As Color = Color.White
        Dim defaufl_forecolor As Color = Color.Black
        btnSDL_Alle.BackColor = defaufl_color : btnSDL_Alle.ForeColor = defaufl_forecolor : btnSDL_Alle.FlatAppearance.BorderSize = 0
        btnSDL_IDS.BackColor = defaufl_color : btnSDL_IDS.ForeColor = defaufl_forecolor : btnSDL_IDS.FlatAppearance.BorderSize = 0
        btnSDL_UTA.BackColor = defaufl_color : btnSDL_UTA.ForeColor = defaufl_forecolor : btnSDL_UTA.FlatAppearance.BorderSize = 0
        btnSDL_DouBox.BackColor = defaufl_color : btnSDL_DouBox.ForeColor = defaufl_forecolor : btnSDL_DouBox.FlatAppearance.BorderSize = 0
        btnSDL_ECOTAX.BackColor = defaufl_color : btnSDL_ECOTAX.ForeColor = defaufl_forecolor : btnSDL_ECOTAX.FlatAppearance.BorderSize = 0
        btnSDL_FREJUS.BackColor = defaufl_color : btnSDL_FREJUS.ForeColor = defaufl_forecolor : btnSDL_FREJUS.FlatAppearance.BorderSize = 0
        btnSDL_MautAT.BackColor = defaufl_color : btnSDL_MautAT.ForeColor = defaufl_forecolor : btnSDL_MautAT.FlatAppearance.BorderSize = 0
        btnSDL_MautDE.BackColor = defaufl_color : btnSDL_MautDE.ForeColor = defaufl_forecolor : btnSDL_MautDE.FlatAppearance.BorderSize = 0
        btnSDL_MautIT.BackColor = defaufl_color : btnSDL_MautIT.ForeColor = defaufl_forecolor : btnSDL_MautIT.FlatAppearance.BorderSize = 0
        btnSDL_MautFR.BackColor = defaufl_color : btnSDL_MautFR.ForeColor = defaufl_forecolor : btnSDL_MautFR.FlatAppearance.BorderSize = 0
        btnSDL_MautPL.BackColor = defaufl_color : btnSDL_MautPL.ForeColor = defaufl_forecolor : btnSDL_MautPL.FlatAppearance.BorderSize = 0
        btnSDL_MautSI.BackColor = defaufl_color : btnSDL_MautSI.ForeColor = defaufl_forecolor : btnSDL_MautSI.FlatAppearance.BorderSize = 0
        btnSDL_MautCZ.BackColor = defaufl_color : btnSDL_MautCZ.ForeColor = defaufl_forecolor : btnSDL_MautCZ.FlatAppearance.BorderSize = 0
        btnSDL_Hugo.BackColor = defaufl_color : btnSDL_Hugo.ForeColor = defaufl_forecolor : btnSDL_Hugo.FlatAppearance.BorderSize = 0
        btnSDL_MautMSE.BackColor = defaufl_color : btnSDL_MautMSE.ForeColor = defaufl_forecolor : btnSDL_MautMSE.FlatAppearance.BorderSize = 0
        btnSDL_MotorWay.BackColor = defaufl_color : btnSDL_MotorWay.ForeColor = defaufl_forecolor : btnSDL_MotorWay.FlatAppearance.BorderSize = 0
        btnSDL_Woelfl.BackColor = defaufl_color : btnSDL_Woelfl.ForeColor = defaufl_forecolor : btnSDL_Woelfl.FlatAppearance.BorderSize = 0
        btnMANAbgasplakette.BackColor = defaufl_color : btnMANAbgasplakette.ForeColor = defaufl_forecolor : btnMANAbgasplakette.FlatAppearance.BorderSize = 0
        btnSDL_PLOSE.BackColor = defaufl_color : btnSDL_PLOSE.ForeColor = defaufl_forecolor : btnSDL_PLOSE.FlatAppearance.BorderSize = 0
        btnSDL_PLOSE_IT.BackColor = defaufl_color : btnSDL_PLOSE_IT.ForeColor = defaufl_forecolor : btnSDL_PLOSE_IT.FlatAppearance.BorderSize = 0
        btnSDL_PLOSE_CZ.BackColor = defaufl_color : btnSDL_PLOSE_CZ.ForeColor = defaufl_forecolor : btnSDL_PLOSE_CZ.FlatAppearance.BorderSize = 0
        btnVERAGParkplatz.BackColor = defaufl_color : btnVERAGParkplatz.ForeColor = defaufl_forecolor : btnVERAGParkplatz.FlatAppearance.BorderSize = 0


        b.FlatAppearance.BorderSize = 1
        b.BackColor = SystemColors.ButtonHighlight
        b.ForeColor = Color.Black
        aktbtn = b.Name

        If dgvSDL.Columns("SDLNr") IsNot Nothing Then

            If aktbtn = "btnSDL_Alle" Then
                dgvSDL.Columns("SDLNr").Visible = True
                '     dgvSDL.ReadOnly = True
                '    Button11.Enabled = False
            Else
                dgvSDL.Columns("SDLNr").Visible = False
                '    dgvSDL.ReadOnly = False
            End If
        End If

        ' If kdNr_filter Then
        'initKDFilter()
        ' End If
        ' initFilter()
    End Sub

    Sub initKDFilter()
        Button5.Enabled = False
        dgvSDL.Columns("KundenNr").ReadOnly = True
        '  dgvSDL.DataSource.Columns("KundenNr").DefaultValue = kdNr
        dgvSDL.Columns("KundenNr").Visible = False
        Try

            dgvFILTER.Columns("KundenNr").ReadOnly = True
            '  dgvSDL.DataSource.Columns("KundenNr").DefaultValue = kdNr
            dgvFILTER.Columns("KundenNr").Visible = False
            'DirectCast(pnlFilterInside.Controls("txtSrch_KundenNr"), TextBox).Text = kdNr
            'DirectCast(pnlFilterInside.Controls("txtSrch_KundenNr"), TextBox).Enabled = False
            '  DirectCast(pnlFilterInside.Controls("txtSrch_KundenNr"), TextBox).ReadOnly = True
            '  initSearch(pnlFilterInside.Controls("txtSrch_KundenNr"), New EventArgs)
        Catch ex As Exception
            '  MsgBox(ex.Message)
        End Try
    End Sub

    Sub SET_SDL(SDLNrTmp, Optional doFilter = False)
        aktSDLNr = SDLNrTmp
        Dim Archiviert = ""
        Select Case cbxArchiv.CheckState
            Case CheckState.Checked
                Archiviert = " AND Archiviert=1 "
            Case CheckState.Unchecked
                Archiviert = " AND Archiviert=0 "
        End Select
        Dim SQL_STR = ""
        Select Case SDLNrTmp
            Case 100 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, (SELECT TOP 1 [CustomerCode] FROM [VERAG].[dbo].[tbl_IDS_Kunden]  WHERE [KdNrVERAG]=KundenNr AND KdNrAlt =0  ORDER BY Zeitstempel DESC) as [IDS-KdNr], KartenNr, GültigBis, PIN,  Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=100"
            Case 101 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, KartenSchlüsselNr, GültigBis, PIN, Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter  FROM SDL WHERE SDLNr=101"
            Case 212 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, UTAKundenNr, KartenNr,[CARD-Nr], GültigBis, PIN, Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL INNER JOIN [VERAG].[dbo].Adressen ON [VERAG].[dbo].Adressen.AdressenNr=SDL.KundenNr    WHERE SDLNr=212"
            Case 200 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, [BestellNr],[Umstellungsdatum],KartenNr,OBUID, Vertragsabschlussdatum,Kategorie,Status,Schadstoffklasse, Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=200"
            Case 201 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, KartenNr, Vermerk ,Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, LKWAbgemeldet, Partner,BenutzerNr,FlottenPIN,MasterPIN, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=201"
            Case 202 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [TELEPASS-Kd-Nr], VIACARD,[TELEPASS-Nr], Vermerk,Gesperrt, Defekt, Verloren, Gestohlen, Retourniert,TelepassErsatzkarte,  SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=202"
            Case 203 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, KartenNr, Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Retourniert, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=203"
            Case 213 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, KartenNr, OBUID, PIN, /*GültigBis,*/Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Retourniert, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=213"
            Case 214 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, /*KartenNr,*/ OBUID, PIN, PLOSEKundenNr, /*GültigBis,*/Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Retourniert, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL INNER JOIN [VERAG].[dbo].Adressen ON [VERAG].[dbo].Adressen.AdressenNr=SDL.KundenNr  WHERE SDLNr=214"
            Case 215 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [TELEPASS-Nr], PLOSEKundenNr, /*GültigBis,*/Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Retourniert, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL INNER JOIN [VERAG].[dbo].Adressen ON [VERAG].[dbo].Adressen.AdressenNr=SDL.KundenNr   WHERE SDLNr=215"
            Case 216 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, KartenNr, OBUID, PIN, PLOSEKundenNr, /*GültigBis,*/Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Retourniert, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL INNER JOIN [VERAG].[dbo].Adressen ON [VERAG].[dbo].Adressen.AdressenNr=SDL.KundenNr   WHERE SDLNr=216"
            Case 209 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [MSE-Kd-Nr], KartenNr, Vermerk,Gesperrt, Defekt, Verloren, Gestohlen, Retourniert,  SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=209"
            Case 210 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [MSE-Kd-Nr], KartenNr, OBUID, [SERIE-Nr],Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Retourniert, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=210"
            Case 208 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [MSE-Kd-Nr], KartenNr, GültigBis,Vermerk,Gesperrt, Defekt, Verloren, Gestohlen, Retourniert,  SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=208"
            Case 205 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [CLIENT-Nr] , [MOTORWAY-CARD-Nr], [CARD-Nr], GültigBis, Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=205"
            Case 211 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [MSE-Kd-Nr], [PAN-Nr], [SERIE-Nr], GültigBis,Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Retourniert, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=211"
            Case 207 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [MSE-Kd-Nr], [FREJUS-CARD-Nr], ECO, GültigBis,Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=207"
            Case 206 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, [MSE-Kd-Nr], [PAN-Nr], [SERIE-Nr], GültigBis,Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=206"
            Case 500 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte,SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=500"
            Case 501 : SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr, KfzKennzeichen, History, Bestelldatum, Lieferdatum, KartenNr,Fahrer,Kaution, Vermerk,Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte,  SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL WHERE SDLNr=501"
            Case Else
                SQL_STR = "SELECT " & IIf(cbxMax200Eintrage.Checked, " top 200 ", "") & " KundenNr, SDL.SDLNr,SDLBez, KfzKennzeichen, History, Vermerk, Gesperrt, Defekt, Verloren, Gestohlen, Ersatzkarte, SDL.Erfassungsdatum, SDL.Änderungsdatum, SDL.Sachbearbeiter FROM SDL INNER JOIN Speditionsdienstleistungen ON Speditionsdienstleistungen.SDLNr=SDL.SDLNr"
                SQL_STR &= " AND Speditionsdienstleistungen.SDLTypNr IN (1,2)  "
        End Select
        SQL_STR &= Archiviert
        ' clearFilter() 

        newBinding(SDLNrTmp, SQL_STR, doFilter)
        initBtnClick(getSDLNrButton(SDLNrTmp))
        If SDLNrTmp = -1 Then
            With dgvSDL
                .Columns("KundenNr").Visible = True
                .Columns("SDLNr").Visible = True
            End With
        End If

        initAllg()
        dgvSDL.Width = 100
        dgvSDL.Height = 100
        dgvSDL.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

        initRtbVermerk(SDLNrTmp, kdNr)

        initDGVWidth() 'vor Filter, damit richtige Größe
        If Not doFilter Then initFilter()

        '  redRows()
        ' initFilter()
    End Sub

    Function getSDLNrButton(SDLNrTmp) As Object
        Select Case SDLNrTmp
            Case 100 : Return btnSDL_IDS
            Case 101 : Return btnSDL_Woelfl
            Case 212 : Return btnSDL_UTA
            Case 200 : Return btnSDL_MautAT
            Case 201 : Return btnSDL_MautDE
            Case 202 : Return btnSDL_MautIT
            Case 203 : Return btnSDL_MautCZ
            Case 213 : Return btnSDL_Hugo
            Case 214 : Return btnSDL_PLOSE
            Case 215 : Return btnSDL_PLOSE_IT
            Case 216 : Return btnSDL_PLOSE_CZ
            Case 209 : Return btnSDL_MautPL
            Case 210 : Return btnSDL_MautSI
            Case 208 : Return btnSDL_MautMSE
            Case 205 : Return btnSDL_MotorWay
            Case 211 : Return btnSDL_ECOTAX
            Case 207 : Return btnSDL_FREJUS
            Case 206 : Return btnSDL_DouBox
            Case 500 : Return btnMANAbgasplakette
            Case 501 : Return btnVERAGParkplatz
            Case Else : Return btnSDL_Alle
        End Select
    End Function
    Private Sub btnSDL_Alle_Click(sender As Object, e As EventArgs) Handles btnSDL_Alle.Click
        SET_SDL(-1)
    End Sub

    Private Sub btnSDL_IDS_Click(sender As Object, e As EventArgs) Handles btnSDL_IDS.Click
        SET_SDL(100)
    End Sub

    Private Sub btnSDL_Woelfl_Click(sender As Object, e As EventArgs) Handles btnSDL_Woelfl.Click
        SET_SDL(101)
    End Sub

    Private Sub btnSDL_UTA_Click(sender As Object, e As EventArgs) Handles btnSDL_UTA.Click
        SET_SDL(212)
    End Sub

    Private Sub btnSDL_MautAT_Click(sender As Object, e As EventArgs) Handles btnSDL_MautAT.Click
        SET_SDL(200)
    End Sub

    Private Sub btnSDL_MautDE_Click(sender As Object, e As EventArgs) Handles btnSDL_MautDE.Click
        SET_SDL(201)
    End Sub

    Private Sub btnSDL_MautIT_Click(sender As Object, e As EventArgs) Handles btnSDL_MautIT.Click
        SET_SDL(202)
    End Sub

    Private Sub btnSDL_MautCZ_Click(sender As Object, e As EventArgs) Handles btnSDL_MautCZ.Click
        SET_SDL(203)
    End Sub

    Private Sub btnSDL_Hugo_Click(sender As Object, e As EventArgs) Handles btnSDL_Hugo.Click
        SET_SDL(213)
    End Sub

    Private Sub btnSDL_PLOSE_Click(sender As Object, e As EventArgs) Handles btnSDL_PLOSE.Click
        SET_SDL(214)
    End Sub

    Private Sub btnSDL_MautPL_Click(sender As Object, e As EventArgs) Handles btnSDL_MautPL.Click
        SET_SDL(209)
    End Sub

    Private Sub btnSDL_MautSI_Click(sender As Object, e As EventArgs) Handles btnSDL_MautSI.Click
        SET_SDL(210)
    End Sub

    Private Sub btnSDL_MautMSE_Click(sender As Object, e As EventArgs) Handles btnSDL_MautMSE.Click
        SET_SDL(208)
    End Sub

    Private Sub btnSDL_MotorWay_Click(sender As Object, e As EventArgs) Handles btnSDL_MotorWay.Click
        SET_SDL(205)
    End Sub

    Private Sub btnSDL_ECOTAX_Click(sender As Object, e As EventArgs) Handles btnSDL_ECOTAX.Click
        SET_SDL(211)
    End Sub

    Private Sub btnSDL_FREJUS_Click(sender As Object, e As EventArgs) Handles btnSDL_FREJUS.Click
        SET_SDL(207)
    End Sub

    Private Sub btnSDL_DouBox_Click(sender As Object, e As EventArgs) Handles btnSDL_DouBox.Click
        SET_SDL(206)
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnMANAbgasplakette.Click
        SET_SDL(500)
    End Sub

    Private Sub btnVERAGParkplatz_Click(sender As Object, e As EventArgs) Handles btnVERAGParkplatz.Click
        SET_SDL(501)
    End Sub

    Private Sub dgvSDL_ColumnWidthChanged(sender As Object, e As DataGridViewColumnEventArgs) Handles dgvSDL.ColumnWidthChanged
        'initSDLBinding()
        ' initAllg()
        ' If Not txtchanged Then initFilter()
        initfilterColumnsWidth()
    End Sub

    Sub initfilterColumnsWidth()

        If dgvFILTER.ColumnCount > 0 AndAlso dgvFILTER.ColumnCount = dgvSDL.ColumnCount Then

            dgvFILTER.Width = dgvSDL.Width
            For Each c As DataGridViewColumn In dgvSDL.Columns
                dgvFILTER.Columns(c.Index).Width = c.Width
            Next

            If kdNr_filter Then
                initKDFilter()
            End If
        End If
    End Sub
    Sub newBinding(sdlNr As Integer, ByVal sql As String, doFilter As Boolean)
        dgvInitWait = True
        ' bindingSDL = Nothing
        dgvSDL.Columns.Clear()
        dgvSDL.VirtualMode = True
        txtchanged = True
        dgvInitWait = True
        If doFilter Then
            Dim filter As String = getFilter()

            If filter <> "" Then sql &= " AND " & filter
            ' sql &= " ORDER BY sdl.[Erfassungsdatum] ASC"
        Else
            '  clearFilter()
        End If
        If kdNr_filter And kdNr > 0 Then sql &= " AND KundenNr=" & kdNr

        ' setBindingstring(sql)


        sql &= " ORDER BY sdl.[Bestelldatum] , sdl.[Erfassungsdatum] ASC ,sdl.ts"
        'sql &= " ORDER BY KundenNr, SDL.SDLNr, KfzKennzeichen, History "

        dgvSDL.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
        '  dgvSDL.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing '; //or even better .DisableResizing. Most time consumption enum is DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders

        dgvSDL.SET_SQL(sql, "SDL", , {"KundenNr", "KfzKennzeichen", "SDLNr", "History"})
        dgvSDL.LOAD()

        lblEinträge.Text = dgvSDL.RowCount & " Einträge"
        If dgvSDL.RowCount >= 200 Then lblEinträge.Text = dgvSDL.RowCount & " Einträge " & IIf(cbxMax200Eintrage.Checked, "(Anzeige auf 200 beschränkt)", "")

        dgvInitWait = False

        

        txtchanged = False
        dgvInitWait = False
        dgvSDL.ClearSelection()
        '     MsgBox(sdlNr)
        btnAbrechnungsblatt.Enabled = False
        btnBenachrichtigungKartenboxen.Enabled = False
        btnBestellformular.Enabled = False

        If kdNr_filter And (sdlNr = 213 Or sdlNr = 210 Or sdlNr = 207) Then
            btnAbrechnungsblatt.Enabled = True
        End If

        btnRetourniert.Enabled = False
        If (sdlNr = 202 Or sdlNr = 203 Or sdlNr = 209 Or sdlNr = 210 Or sdlNr = 211 Or sdlNr = 213 Or sdlNr = 214 Or sdlNr = 215 Or sdlNr = 216) Then
            btnRetourniert.Enabled = True
        End If


        If sdlNr = -1 Then btnBenachrichtigungKartenboxen.Enabled = True

        If sdlNr = 100 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 212 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 202 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 210 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 211 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 213 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 214 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 215 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 216 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 208 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 207 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 101 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 500 Then btnBenachrichtigungKartenboxen.Enabled = True
        If sdlNr = 501 Then btnBenachrichtigungKartenboxen.Enabled = True


        If sdlNr = 203 Then btnBenachrichtigungKartenboxen.Enabled = True 'CZ
        If sdlNr = 209 Then btnBenachrichtigungKartenboxen.Enabled = True 'PL


        If sdlNr = 500 Then btnBestellformular.Enabled = True



        If dgvSDL.RowCount > 0 Then
            dgvSDL.Rows(0).Cells(0).Selected = True
        Else
            '    SplitContainer1.Panel2.Controls.Clear() ' nicht, sonst bei kd-Wechsel keine control mehr
        End If
        ReloadLeistung()
        ' dgvSDL_SelectionChanged(dgvSDL, New EventArgs)
    End Sub



    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles btnFilter.Click
        '     MsgBox(pnlFilterInside.Height)
        Exit Sub
        If pnlTest.Height > 0 Then
            pnlTest.Height = 0
            btnFilter.Text = "Filter einblenden"
        Else
            pnlTest.Height = 39
            btnFilter.Text = "Filter ausblenden"
        End If
    End Sub

 
 
    Private Sub Button4_Click_1(sender As Object, e As EventArgs) Handles Button4.Click
        If SplitContainer1.Panel2Collapsed Then
            SplitContainer1.Panel2Collapsed = False
            dgvSDL_SelectionChanged(dgvSDL, New System.EventArgs)
        Else
            SplitContainer1.Panel2Collapsed = True
        End If

    End Sub

    Sub reClick()
        getSDLNrButton(aktSDLNr).PerformClick()
    End Sub

    Sub refreshDgv(kdNr, SDLNr, Optional Kfz = "", Optional History = "")
        SET_SDL(aktSDLNr, True)

        dgvSDL.ClearSelection()
        If Kfz <> "" And History <> "" Then
            For Each r As DataGridViewRow In dgvSDL.Rows
                If r.Cells("KundenNr").Value = kdNr And
                    r.Cells("SDLNr").Value = SDLNr And
                    r.Cells("KfzKennzeichen").Value = Kfz And
                    r.Cells("History").Value = History Then
                    r.Selected = True
                    Exit For
                End If
            Next
        End If

    End Sub



    Private Sub UsrCntlDatenDetails1_Changed(kdNr, Kfz, SDLNr, History) Handles UsrCntlDatenDetails1.Changed
        'refreshDgv(kdNr, SDLNr, Kfz, History)'?????????????? ausgebelndet,was das ein VErsuch? 31.07.2017
        dgvSDL.VALUE_CHANGED = True
    End Sub

    Private Sub datadgvSDL_SelectionChanged(kdNr, Kfz, SDLNr, History) Handles UsrCntlDatenDetails1.DataChanged
        '    refreshDgv(kdNr, SDLNr, Kfz, History)
        dgvSDL.VALUE_CHANGED = True
        Exit Sub

        dgvInitWait = True
        dgvSDL.RELOAD()
        dgvInitWait = False
    End Sub
    '    Private Sub dgvSDL_SelectionChanged(sender As Object, e As EventArgs) Handles dgvSDL.SelectionChanged

    Private Sub dgvSDL_KeyDown(sender As Object, e As KeyEventArgs) Handles dgvSDL.KeyUp
        If e.KeyCode = Keys.Up Or e.KeyCode = Keys.Down Or e.KeyCode = Keys.End Or e.KeyCode = Keys.Home Then '?POS1
            ReloadLeistung()
        End If
    End Sub
    Private Sub dgvSDL_SelectionChanged(sender As Object, e As EventArgs) Handles dgvSDL.Click
        ReloadLeistung()
    End Sub
    Sub ReloadLeistung()

        btnDel.Enabled = (dgvSDL.SelectedRows.Count > 0)
        initRtbVermerk(-1)

        '   MsgBox(dgvInitWait)
        If Not dgvInitWait Then
            Try
                If dgvSDL.SelectedRows.Count > 0 Then
                    '  MsgBox("So")
                    UsrCntlDatenDetails1.Visible = True
                    initRtbVermerk(dgvSDL.SelectedRows(0).Cells("SDLNr").Value, dgvSDL.SelectedRows(0).Cells("KundenNr").Value)
                    ' RichTextBoxVermerk.Text = SQL.getValueTxtBySql("SELECT [Vermerk]  FROM [KundenSDL] WHERE [KundenNr]=" & dgvSDL.SelectedRows(0).Cells("KundenNr").Value & " AND  [SDLNr]=" & dgvSDL.SelectedRows(0).Cells("SDLNr").Value, "SDL")
                    If Not SplitContainer1.Panel2Collapsed Then
                        Me.Cursor = Cursors.WaitCursor
                        If kdNr_filter = False Then UsrCntlDatenDetails1.showFirma = True
                        '  MsgBox(dgvSDL.SelectedRows(0).Cells("KfzKennzeichen").Value)
                        UsrCntlDatenDetails1.init(dgvSDL.SelectedRows(0).Cells("KundenNr").Value, dgvSDL.SelectedRows(0).Cells("KfzKennzeichen").Value, dgvSDL.SelectedRows(0).Cells("SDLNr").Value, dgvSDL.SelectedRows(0).Cells("History").Value)
                        Me.Cursor = Cursors.Default
                    End If
                Else
                    UsrCntlDatenDetails1.Visible = False
                End If
            Catch ex As Exception
                'Neuer eintrag
                MsgBox(ex.Message & ex.StackTrace)
            End Try

        End If

    End Sub

    Sub initRtbVermerk(SdlNr As Integer, Optional KdNr As Integer = -1)
        RichTextBoxVermerk.Text = ""
        If SdlNr > 0 And KdNr > 0 Then
            RichTextBoxVermerk.Text = SQL.getValueTxtBySql("SELECT [Vermerk]  FROM [KundenSDL] WHERE [KundenNr]=" & KdNr & " AND  [SDLNr]=" & SdlNr, "SDL")
        End If

        If RichTextBoxVermerk.Text <> "" Then
            RichTextBoxVermerk.BackColor = Color.LightCyan
        Else
            RichTextBoxVermerk.BackColor = Color.FromArgb(240, 240, 240)
        End If

    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        If Not kdNr_filter Then
            If dgvSDL.SelectedCells.Count > 0 Then
                If IsNumeric(dgvSDL.CurrentRow.Cells("KundenNr").Value) Then
                    cProgramFunctions.openKundenblatt(dgvSDL.CurrentRow.Cells("KundenNr").Value, Me.FindForm, True)
                    'Dim pf As New cProgramFunctions
                    'pf.openKundenblatt(dgvSDL.CurrentRow.Cells("KundenNr").Value)
                End If
            End If
        End If
    End Sub



    Private Sub dgvSDL_UserAddedRow(sender As Object, e As DataGridViewRowEventArgs) Handles dgvSDL.UserAddedRow
        dgvSDL.CurrentRow.Cells("SDLNr").Value = aktSDLNr
    End Sub


    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", Me.FindForm) Then
            MsgBox("Keine Berechtigung!")
            Exit Sub
        End If
        Dim kdTMP = kdNr
        Dim kfzTmp = ""
        Dim SDLNrTMP = aktSDLNr
        Dim histTmp = -1

        NewData(kdTMP, kfzTmp, SDLNrTMP, histTmp)
        SET_SDL(aktSDLNr, True)
        SelectRow(kdTMP, kfzTmp, SDLNrTMP, histTmp)
    End Sub

    Sub NewData(ByRef kdnrTMP, ByRef kfzTMP, ByRef SDLNrTMP, ByRef historyTMP)
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", Me.FindForm) Then
            MsgBox("Keine Berechtigung!")
            Exit Sub
        End If

        If kdnrTMP < 0 Then
            If kdNr > 0 Then
                kdnrTMP = kdNr
            Else
                Try : kdnrTMP = CInt(dgvSDL.CurrentRow.Cells("KundenNr").Value) : Catch : End Try
            End If
        End If

        If SDLNrTMP < 0 Then
            If IsNumeric(aktSDLNr) AndAlso aktSDLNr > 0 Then
                SDLNrTMP = aktSDLNr
            Else
                Try : SDLNrTMP = CInt(aktSDLNr) : Catch : End Try
            End If
        End If

        Select Case cProgramFunctions.newFrmData(Me.FindForm, kdnrTMP, SDLNrTMP, kfzTMP, historyTMP)
            Case "OK" : SET_SDL(aktSDLNr, True)
            Case "OK_NEW" : NewData(kdnrTMP, kfzTMP, SDLNrTMP, historyTMP)
        End Select
    End Sub

    Sub SelectRow(kdnr, kfz, SDLNr, history)
        dgvInitWait = True
        dgvSDL.ClearSelection()
        For Each r As DataGridViewRow In dgvSDL.Rows
            If r.Cells("KundenNr").Value = kdnr AndAlso
                r.Cells("SDLNr").Value = SDLNr AndAlso
                r.Cells("KfzKennzeichen").Value = kfz AndAlso
                r.Cells("History").Value = history Then
                r.Selected = True
                dgvSDL.FirstDisplayedScrollingRowIndex = r.Index
                Exit For
            End If
        Next
        dgvInitWait = False
        ReloadLeistung()
        dgvSDL.PerformLayout()
    End Sub
    Private Sub dgvSDL_RowHeaderMouseDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSDL.CellDoubleClick 'dgvSDL.RowHeaderMouseDoubleClick
        Exit Sub ' keine Anzeige mehr  bei Doppelklick
        Try

            Dim frmGrayOut = cProgramFunctions.grayoutForm(Me)
            Dim frmNewData As New frmCardDetails
            'av.ShowDialog(frmGrayOut)

            Try : frmNewData.kdnr = dgvSDL.CurrentRow.Cells("KundenNr").Value : Catch : End Try
            frmNewData.SDLLeistung = dgvSDL.CurrentRow.Cells("SDLNr").Value
            frmNewData.history = dgvSDL.CurrentRow.Cells("History").Value
            frmNewData.addnew = False
            frmNewData.KfzKennzeichen = dgvSDL.CurrentRow.Cells("KfzKennzeichen").Value
            frmNewData.Text = "Daten bearbeiten"
            If frmNewData.ShowDialog(frmGrayOut) = DialogResult.OK Then
                SET_SDL(aktSDLNr, True)
            End If
            frmGrayOut.Close()


            ' Dim frmNewData As New frmNewData
            ' Try : frmNewData.kdnr = dgvSDL.CurrentRow.Cells("KundenNr").Value : Catch : End Try
            ' frmNewData.SDLLeistung = dgvSDL.CurrentRow.Cells("SDLNr").Value
            'frmNewData.history = dgvSDL.CurrentRow.Cells("History").Value
            'frmNewData.addnew = False
            'frmNewData.KfzKennzeichen = dgvSDL.CurrentRow.Cells("KfzKennzeichen").Value
            ' frmNewData.Text = "Daten bearbeiten"
            ' If frmNewData.ShowDialog(Me) = DialogResult.OK Then
            'initSearch(Me, New EventArgs)
            '  End If

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

    Private Sub btnSDL_MautFR_Click(sender As Object, e As EventArgs) Handles btnSDL_MautFR.Click

    End Sub

    Private Sub Button8_Click(sender As Object, e As EventArgs) Handles btnDel.Click
        If Not VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("MDM_Leistungen_bearbeiten", Me.FindForm) Then
            MsgBox("Keine Berechtigung!")
            Exit Sub
        End If
        If dgvSDL.SelectedRows.Count > 20 Then MsgBox("Es können nicht mehr als 20 Zeilen gelöscht werden!") : Exit Sub
        If dgvSDL.SelectedRows.Count = 0 Then Exit Sub

         
        Dim txt As String = "Möchten Sie den Eintrag / die Einträge wirklich löschen?" & vbNewLine & vbNewLine
        For Each r As DataGridViewRow In dgvSDL.SelectedRows
            txt &= r.Cells("KfzKennzeichen").Value & " - " & r.Cells("SDLNr").Value & vbNewLine
        Next
        Dim donotdel = False
        If vbYes = MsgBox(txt, vbYesNoCancel) Then
            For Each r As DataGridViewRow In dgvSDL.SelectedRows
                Dim kdTMP = r.Cells("KundenNr").Value
                Dim sdlTMP = r.Cells("SDLNr").Value
                Dim kfzKzTMP = r.Cells("KfzKennzeichen").Value
                Dim hisTMP = r.Cells("History").Value
                If sdlTMP = 501 Then
                    donotdel = True
                Else
                    SQL.doSQL("DELETE TOP (1) FROM SDL WHERE KundenNr='" & kdTMP & "' AND  KfzKennzeichen='" & kfzKzTMP & "' AND SDLNr='" & sdlTMP & "' AND History='" & hisTMP & "'", "SDL", True)
                End If
            Next
            If donotdel Then MsgBox("VERAG-Parkplatzkarten können nicht gelöscht werden. Bitte auf gesperrt/verloren/gestohlen/defekt setzen!")

            SET_SDL(aktSDLNr, True)
        End If
    End Sub

    'Private Sub Button8_Click_1(sender As Object, e As EventArgs) Handles Button8.Click
    '    cProgramFunctions.genExcelFromDGV(dgvSDL, True)
    'End Sub

    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles btnBenachrichtigungKartenboxen.Click
        Try
            Dim kdNrTmp = -1
            If dgvSDL.SelectedRows.Count > 0 Then kdNrTmp = CInt(dgvSDL.SelectedRows(0).Cells("KundenNr").Value)
           
            Dim f As New frmSDLAbholungEintrag(kdNrTmp, aktSDLNr)
            f.Show()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        'If dgvSDL.SelectedRows.Count = 0 Then Exit Sub
        'Dim f As New frmBenachrichtignunNeueKartenBoxen(Now, Now, dgvSDL.SelectedRows(0).Cells("KundenNr").Value, aktSDLNr)
        'f.ShowDialog()

    End Sub


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnAbrechnungsblatt.Click
        Me.Cursor = Cursors.WaitCursor
        Dim s = InputBox("Bitte das Datum eingeben:", "Datum", Now.ToShortDateString)
        If IsDate(s) Then
            Dim print As New frmPrintLayout
            print.Text = "Abrechnungsblatt"
            Dim rpt As New rptSDLAbrechnungsblatt
            rpt.KdNr = kdNr
            rpt.sdlNr = aktSDLNr
            rpt.datum = CDate(s)
            rpt.sachbearbeiter = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME
            print.Viewer.LoadDocument(rpt)
            print.Viewer.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
            print.Show()
        Else
            MsgBox("Datum nicht korrekt!")
        End If
        Me.Cursor = Cursors.Default
    End Sub
    Private Sub Button10_Click(sender As Object, e As EventArgs) Handles Button10.Click

        cMDMAuswertung.genUeberfaelligeBestellungen(Me.FindForm, Now.AddMonths(-6), Now, VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME, kdNr, IIf(IsNumeric(aktSDLNr), aktSDLNr, -1))


        Exit Sub

        If kdNr > 0 Then
            cMDMAuswertung.genUeberfaelligeBestellungen(Me.FindForm, Now.AddMonths(-6), Now, VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME, kdNr, IIf(IsNumeric(aktSDLNr), aktSDLNr, -1))
        ElseIf dgvSDL.SelectedRows.Count > 0 Then
            cMDMAuswertung.genUeberfaelligeBestellungen(Me.FindForm, Now.AddMonths(-6), Now, VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME, dgvSDL.CurrentRow.Cells("KundenNr").Value, IIf(IsNumeric(aktSDLNr), aktSDLNr, -1))
        End If
    End Sub

    Private Sub Button11_Click(sender As Object, e As EventArgs) Handles Button11.Click
        If kdNr > 0 Then
            cMDMAuswertung.genSDLrief(Me.FindForm, kdNr, IIf(IsNumeric(aktSDLNr), aktSDLNr, -1), VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME, cbxArchiv.Checked)
        ElseIf dgvSDL.SelectedRows.Count > 0 Then
            cMDMAuswertung.genSDLrief(Me.FindForm, dgvSDL.CurrentRow.Cells("KundenNr").Value, IIf(IsNumeric(aktSDLNr), aktSDLNr, -1), VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME, cbxArchiv.Checked)
        End If
    End Sub
    '  Private Sub FlatButton1_Click(sender As Object, e As MouseEventArgs) Handles Button8.MouseClick ', Button13.Click
    '     sender.ContextMenuStrip = cntxtExcel
    '     sender.ContextMenuStrip.Show(sender, e.Location)
    'End Sub

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

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

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles btnRetourniert.Click
        Dim kdNrTMP = ""
        If kdNr <= 0 Then
            kdNrTMP = InputBox("Bitte die Kundennummer eingeben:", "Kundennummer")
            If Not IsNumeric(kdNrTMP) OrElse kdNrTMP <= 0 Then
                MsgBox("Kundennummer falsches Format!")
                Exit Sub
            End If
        Else
            kdNrTMP = kdNr
        End If

        Dim s = InputBox("Bitte das Datum eingeben:", "Datum", Now.ToShortDateString)
        If IsDate(s) Then
            openWordRetourniert(aktSDLNr, kdNrTMP, CDate(s))
        Else
            MsgBox("Datum nicht korrekt!")
        End If

    End Sub

    Sub openWordRetourniert(sdlnr As Integer, kdNr As Integer, datum As Date)
        If Not My.Computer.FileSystem.DirectoryExists(Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\tmp\") Then
            My.Computer.FileSystem.CreateDirectory(Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\tmp\")
        End If
        Dim tmpPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Personal) & "\VERAG\tmp\tmp.doc"
        Dim pfad = ""


        Select Case sdlnr
            Case 202 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\TELEPASS.doc"
            Case 203 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\CZ.doc"
            Case 209 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\VIATOLL.doc"
            Case 210 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\SI.doc"
            Case 211 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\MULTIBOX.doc"
            Case 213 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\HUGO.doc"
            Case 214 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\PLOSE.doc"
            Case 215 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\PLOSE_IT.doc"
            Case 216 : pfad = AppDomain.CurrentDomain.BaseDirectory & "Resources\MDM_Schreiben\Retour\PLOSE_CZ.doc"
        End Select

        If Not System.IO.File.Exists(pfad) Then
            MsgBox("Problem beim Auflösen des Pfades.")
            Exit Sub
        End If

        Dim oWord As New Microsoft.Office.Interop.Word.Application
        Dim odoc As Microsoft.Office.Interop.Word.Document
        Try
            oWord.Visible = True 'Word sehen zum Test?
            odoc = oWord.Documents.Open(pfad)
            odoc.SaveAs(tmpPath)
            odoc.Activate()

            Select Case sdlnr
                Case 202 : odoc = getWordRetourniert_ItTelepass(odoc, kdNr, datum)
                Case 203 : odoc = getWordRetourniert_CZ(odoc, kdNr, datum)
                Case 209 : odoc = getWordRetourniert_PL(odoc, kdNr, datum)
                Case 210 : odoc = getWordRetourniert_SI(odoc, kdNr, datum)
                Case 211 : odoc = getWordRetourniert_MULTI(odoc, kdNr, datum)
                Case 213 : odoc = getWordRetourniert_HUGO(odoc, kdNr, datum)
                Case 214 : odoc = getWordRetourniert_PLOSE(odoc, kdNr, datum)
                Case 215 : odoc = getWordRetourniert_PLOSE_IT(odoc, kdNr, datum)
                Case 216 : odoc = getWordRetourniert_PLOSE_CZ(odoc, kdNr, datum)
                Case Else : odoc.Close() : MsgBox("Falsche Leistung")
            End Select

            odoc.Save()

        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
    End Sub

    Function getWordRetourniert_SI(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=210 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            '  Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            '  odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            ' odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.MSEKundenNr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("SERIE-Nr"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = cSqlDb.checkNullStr(r("KartenNr"))
                        oTable.Rows(i + 1).Cells(4).Range.Text = ""
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function

    Function getWordRetourniert_HUGO(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=213 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.MSEKundenNr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("KartenNr"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = cSqlDb.checkNullStr(r("OBUID"))
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function

    Function getWordRetourniert_CZ(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=203 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.MSEKundenNr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("KartenNr"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = ""
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function
    Function getWordRetourniert_PLOSE_CZ(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=216 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.PLOSE_KundenNr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("KartenNr"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = cSqlDb.checkNullStr(r("OBUID"))
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function
    Function getWordRetourniert_PLOSE(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=214 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.PLOSE_KundenNr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("KartenNr"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = cSqlDb.checkNullStr(r("OBUID"))
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function

    Function getWordRetourniert_MULTI(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=211 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.MSEKundenNr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("PAN-Nr"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = cSqlDb.checkNullStr(r("SERIE-Nr"))
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function

    Function getWordRetourniert_PL(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=209 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.MSEKundenNr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("KartenNr"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = ""
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function

    Function getWordRetourniert_ItTelepass(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=202 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.TELEPASS_Kd_Nr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("VIACARD"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = cSqlDb.checkNullStr(r("TELEPASS-Nr"))
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function

    Function getWordRetourniert_PLOSE_IT(odoc As Microsoft.Office.Interop.Word.Document, kdNr As Integer, datum As Date) As Microsoft.Office.Interop.Word.Document
        Try
            Dim dt As DataTable = SQL.loadDgvBySql("SELECT * FROM SDL WHERE KundenNr=" & kdNr & " AND SDLNr=215 AND Retourniert=1 AND RetourniertAm between '" & datum.ToShortDateString & " 00:00:00' and '" & datum.ToShortDateString & " 23:59:59'")
            Dim KUNDE = kundenSQL.getKundeFMZOLLByKdNr(kdNr)
            If KUNDE Is Nothing Then MsgBox("Kunde nicht gefunden!") : Return odoc
            Dim PartnerKdNrFromFMZOLL As cPartnerKdNRFMZoll = kundenSQL.getPartnerKdNrFromFMZOLL(kdNr)

            Dim oTable As Word.Table
            odoc.FormFields("Anzahl").Range.Text = dt.Rows.Count
            odoc.FormFields("KdName").Range.Text = KUNDE.Name_1 & " " & KUNDE.Name_2
            odoc.FormFields("KdStrasse").Range.Text = KUNDE.Straße
            odoc.FormFields("KdOrt").Range.Text = KUNDE.LandKz & " " & KUNDE.PLZ & " " & KUNDE.Ort
            odoc.FormFields("KdNrVERAG").Range.Text = KUNDE.KundenNr
            odoc.FormFields("KdNrMST").Range.Text = PartnerKdNrFromFMZOLL.PLOSE_KundenNr
            odoc.FormFields("Sachbearbeiter").Range.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME

            If odoc.Range.Bookmarks.Exists("TabelleKarten2") Then
                If odoc.Bookmarks("TabelleKarten2").Range.Tables.Count > 0 Then
                    oTable = odoc.Bookmarks("TabelleKarten2").Range.Tables(1)
                    Dim i = 1
                    For Each r As DataRow In dt.Rows
                        oTable.Rows(i + 1).Cells(1).Range.Text = cSqlDb.checkNullStr(r("KfzKennzeichen"))
                        oTable.Rows(i + 1).Cells(2).Range.Text = cSqlDb.checkNullStr(r("VIACARD"))
                        oTable.Rows(i + 1).Cells(3).Range.Text = cSqlDb.checkNullStr(r("TELEPASS-Nr"))
                        If i < dt.Rows.Count Then oTable.Rows.Add()
                        i += 1
                    Next
                End If
            Else
                MessageBox.Show("Textmarke nicht vorhanden!")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.ToString)
        End Try
        Return odoc
    End Function

    Private Sub Button8_Click_1(sender As Object, e As EventArgs) Handles Button8.Click
        Me.Cursor = Cursors.WaitCursor
        cProgramFunctions.genExcelFromDGV_NEW(dgvSDL, True, True)
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Button1_Click_2(sender As Object, e As EventArgs) Handles Button1.Click
        dgvSDL.RELOAD()
    End Sub


    Private Sub dgvSDL_RELOADED() Handles dgvSDL.RELOADED
        redRows()
    End Sub

    Private Sub usrCntlKartenDaten_SizeChanged(sender As Object, e As EventArgs) Handles Me.SizeChanged
        '  initDGVWidth()
    End Sub


    Dim vval As Integer
    Private Sub dgvSDL_GotFocus(sender As Object, e As EventArgs) Handles dgvSDL.GotFocus
        'dgvSDL.VerticalScrollingOffset = vval
        SplitContainer1.Panel1.VerticalScroll.Value = vval
    End Sub

    Private Sub dgvSDL_Enter(sender As Object, e As EventArgs) Handles dgvSDL.Enter
        vval = SplitContainer1.Panel1.VerticalScroll.Value
    End Sub

    
    Private Sub dgvFILTER_SelectionChanged(sender As Object, e As EventArgs) Handles dgvFILTER.SelectionChanged
        dgvFILTER.ClearSelection()
    End Sub

    Private Sub dgvFILTER_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvFILTER.CellContentClick
        If dgvFILTER.Columns(e.ColumnIndex).GetType Is GetType(DataGridViewCheckBoxColumn) Then
            dgvSDL.Focus()
        End If
    End Sub


    Private Sub dgvFILTER_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles dgvFILTER.CellValueChanged
        SET_SDL(aktSDLNr, True)
        initfilterColumnsWidth()
    End Sub

     

    Private Sub btnBestellformular_Click(sender As Object, e As EventArgs) Handles btnBestellformular.Click

        Try
            Dim kdNrTmp = -1
            If dgvSDL.SelectedRows.Count > 0 Then kdNrTmp = CInt(dgvSDL.SelectedRows(0).Cells("KundenNr").Value)
            Dim f As New frmSDLBestellungEintrag(kdNrTmp, aktSDLNr)
            f.Show()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
     

    End Sub

    Private Sub btnSDL_PLOSE_IT_Click(sender As Object, e As EventArgs) Handles btnSDL_PLOSE_IT.Click
        SET_SDL(215)
    End Sub

    Private Sub btnSDL_PLOSE_CZ_Click(sender As Object, e As EventArgs) Handles btnSDL_PLOSE_CZ.Click
        SET_SDL(216)
    End Sub
End Class
