Imports System.Data.SqlClient
Imports System.Globalization

Public Class frmKassenbuchSuche
    Dim SQL As New SQL
    Dim DGV = "B"

    Private Sub btnSuche_Click(sender As Object, e As EventArgs) Handles btnSuche.Click
        Me.Cursor = Cursors.WaitCursor


        With DataGridView
            .Columns.Clear()
            If DGV = "B" Then
                pnlRechts.Enabled = True
                btnDGVBelege.BackColor = Color.SteelBlue
                btnDGVBelege.ForeColor = Color.White
                btnDGVKassenbuch.BackColor = Color.Transparent
                btnDGVKassenbuch.ForeColor = Color.DimGray



                Dim sqlstr = "SELECT b.rksv_BelegId, b.BelegDat, CASE WHEN b.Belegart=1 THEN 'E' ELSE 'A' END as Belegart,CASE WHEN b.Beleg_TYP='E' THEN rksv_umsatz ELSE  (SELECT sum( betrag ) FROM tblEABelegposition WHERE (b.BelegNr = tblEABelegposition.BelegNr) AND (b.BelegDat = tblEABelegposition.BelegDat) AND (b.Benutzer = tblEABelegposition.Benutzer) AND (b.Niederlassung = tblEABelegposition.Niederlassung) AND (b.Mandant = tblEABelegposition.Mandant ) ) END as  Betrag, b.Ordnungsbegriff,  b.BelegNr,  b.Frachtführer, " &
                                               " CASE WHEN b.storniert=1 THEN 'JA' ELSE '' END as [storniert], b.Beleg_TYP ,b.Benutzer , (SELECT cast(ID as varchar(3))+' '+Name FROM [Personal] WHERE [ID]=b.Benutzer) as BenutzerBez " &
                                     "  FROM tblEABelegnummer as b    WHERE 1=1 "

                .SET_SQL(sqlstr & getBelegWhere() & " ORDER BY  b.rksv_BelegId DESC, b.[upsize_ts] desc", "FMZOLL", getBelegList)
                .LOAD()
                If .RowCount = 0 Then Me.Cursor = Cursors.Default : Exit Sub
                lblErgebnis.Text = "Ergebnisse: " & .RowCount

                .Columns("Betrag").DefaultCellStyle.Format = "C"
                .Columns("Betrag").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
                .Columns("Ordnungsbegriff").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

                .Columns("rksv_BelegId").HeaderText = "Beleg-Nr"
                .Columns("rksv_BelegId").Width = 55
                .Columns("rksv_BelegId").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
                .Columns("BelegDat").HeaderText = "Datum"
                .Columns("BelegDat").Width = 65
                .Columns("BelegNr").HeaderText = "KB-Bel.Nr"
                .Columns("BelegNr").Width = 55
                .Columns("BelegNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
                .Columns("Belegart").HeaderText = "Art"
                .Columns("Belegart").Width = 30
                .Columns("Belegart").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
                .Columns("Ordnungsbegriff").Width = 160
                .Columns("Frachtführer").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                .Columns("Beleg_TYP").Visible = False
                .Columns("storniert").HeaderText = "Storn."
                .Columns("storniert").Width = 45
                .Columns("Benutzer").Visible = False

                '  If master_Kasse Then
                .Columns("BenutzerBez").HeaderText = "Benutzer" 'gibts bei bei master
                'End If

                For Each r As DataGridViewRow In .Rows
                    If r.Cells("storniert").Value = "JA" Then
                        r.DefaultCellStyle.ForeColor = Color.Red
                    End If
                Next

            ElseIf DGV = "KB" Then

                pnlRechts.Enabled = False
                btnDGVKassenbuch.BackColor = Color.SteelBlue
                btnDGVKassenbuch.ForeColor = Color.White
                btnDGVBelege.BackColor = Color.Transparent
                btnDGVBelege.ForeColor = Color.DimGray



                Dim sqlstr = "SELECT [JournalNr],[BelegDat],[BelegNr],CASE WHEN Belegart=1 THEN 'E' ELSE 'A' END as Belegart,[Buchungstext],([Betrag]+[Steuerbetrag]) as Brutto,[Konto],[Soll],[Haben],Steuerbetrag as Steuer,tblKassenbuch.Benutzer, isnull([Finanzwege], '-') as ZM  " &
                   " FROM Personal INNER JOIN tblKassenbuch ON Personal.ID = tblKassenbuch.Benutzer  " &
                   "    WHERE 1=1 "

                .SET_SQL(sqlstr & getKassenbuchWhere() & " ORDER BY JournalNr DESC", "FMZOLL", getKassenbuchList)
                .LOAD()
                If .RowCount = 0 Then Me.Cursor = Cursors.Default : Exit Sub

                .Columns("JournalNr").Width = 55
                .Columns("JournalNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
                .Columns("Brutto").DefaultCellStyle.Format = "C"
                .Columns("Brutto").Width = 80
                .Columns("Brutto").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopRight
                .Columns("BelegDat").HeaderText = "Datum"
                .Columns("BelegDat").Width = 65
                .Columns("BelegNr").HeaderText = "KB-Bel.Nr"
                .Columns("BelegNr").Width = 55
                .Columns("BelegNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
                .Columns("Belegart").HeaderText = "Art"
                .Columns("Belegart").Width = 30
                .Columns("Belegart").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
                .Columns("Buchungstext").MinimumWidth = 60
                .Columns("Buchungstext").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
                .Columns("Konto").Width = 40
                .Columns("ZM").Width = 40
                .Columns("Soll").Width = 80
                .Columns("Soll").DefaultCellStyle.Format = "C"
                .Columns("Haben").Width = 80
                .Columns("Haben").DefaultCellStyle.Format = "C"
                .Columns("Steuer").Width = 80
                .Columns("Steuer").DefaultCellStyle.Format = "C"
                .Columns("Benutzer").Visible = False

            End If
        End With



        Me.Cursor = Cursors.Default
    End Sub


    Function getKassenbuchWhere() As String
        Dim sqlstr = ""
        Dim rksv_id = cboKasse._value
        Dim Mandant = "VERA"
        Dim Niederlassung = "VERA"

        Select Case rksv_id
            Case 1 : Mandant = "VERA" : Niederlassung = "SUB"
            Case 2 : Mandant = "VERA" : Niederlassung = "SUB"
            Case 3 : Mandant = "VERA" : Niederlassung = "SUW"
            Case 4 : Mandant = "VERA" : Niederlassung = "WAI"
            Case 5 : Mandant = "VERA" : Niederlassung = "VRR"
            Case 6 : Mandant = "VERA" : Niederlassung = "SUB"
        End Select
         
        '   sqlstr &= " AND  tblKassenbuch.Mandant='" & Mandant & "' AND tblKassenbuch.Niederlassung='" & Niederlassung & "' " & ""
        ' sqlstr &= " AND  tblKassenbuch.Benutzer IN (SELECT ID FROM [Personal] WHERE [Standard_RKSV_KasseId]='" & rksv_id & "')  "
        sqlstr &= " AND  tblKassenbuch.rksv_id='" & rksv_id & "'  "
        If txtAbfertDat.Text <> "" Then
            If txtAbfertDatBis.Text <> "" Then
                sqlstr &= " AND (BelegDat BETWEEN @Datum_von AND @Datum_bis ) "
            Else
                sqlstr &= " AND (BelegDat BETWEEN @Datum_von AND @Datum_von ) "
            End If
        End If

        If txtAuftraggeberKdnr.Text <> "" And IsNumeric(txtAuftraggeberKdnr.Text) Then : sqlstr &= " AND [KundenNr] LIKE @VermittlerKundenNr "
        ElseIf kdtxtAuftraggeber.Text <> "" Then : sqlstr &= " AND  [Name1] LIKE @Vermittler " : End If

        If txtAbfertigungsnummer.Text <> "" Then
            If txtAbfertigungsnummerBis.Text <> "" Then
                sqlstr &= " AND ([AbfertigungsNr] BETWEEN @AbfertigungsNr AND @AbfertigungsNr_bis) "
            Else
                sqlstr &= " AND AbfertigungsNr LIKE @AbfertigungsNr "
            End If
        End If
        If txtUnterNr.Text <> "" Then sqlstr &= " AND [UnterNr] LIKE @UnterNr "
        If cboFiliale._value <> "" Then sqlstr &= " AND [FilialenNr] LIKE @FilialenNr "
        If cboKassier._value <> "" Then sqlstr &= " AND [Benutzer] = @Benutzer "

        If cbxZahlungsmittel._value <> "" Then sqlstr &= " AND [Finanzwege] = @Zahlungsmittel "

        If txtLKWKennzeichen.Text <> "" Then sqlstr &= " AND [LKW Kennzeichen] LIKE @LKW "

        ' If txtSachbearbeiter.Text <> "" Then sqlstr &= " AND [Sachbearbeiter] = @Sachbearbeiter "


        Return sqlstr
    End Function

    Function getKassenbuchList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)

        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Datum_von", txtAbfertDat.Text & " 00:00:00"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Datum_bis", txtAbfertDatBis.Text & " 23:59:59"))

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Vermittler", kdtxtAuftraggeber.Text.Replace("*", "%")))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("VermittlerKundenNr", txtAuftraggeberKdnr.Text.Replace("*", "%")))

        If txtAbfertigungsnummerBis.Text <> "" Then
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("AbfertigungsNr", txtAbfertigungsnummer.Text.Replace("*", "")))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("AbfertigungsNr_bis", txtAbfertigungsnummerBis.Text.Replace("*", "")))
        Else
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("AbfertigungsNr", txtAbfertigungsnummer.Text.Replace("*", "%")))
        End If
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UnterNr", txtUnterNr.Text))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("FilialenNr", cboFiliale._value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Benutzer", cboKassier._value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("LKW", txtLKWKennzeichen.Text.Replace("*", "%").ToUpper))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Zahlungsmittel", cbxZahlungsmittel._value))
        '  list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Sachbearbeiter", txtSachbearbeiter.Text))
        Return list

    End Function


    Function getBelegWhere() As String
        Dim sqlstr = ""
        Dim rksv_id = cboKasse._value
        Dim Mandant = "VERA"
        Dim Niederlassung = "VERA"

        Select Case rksv_id
            Case 1 : Mandant = "VERA" : Niederlassung = "SUB"
        End Select
        '   If cboNiederlassung.Text <> "" Then sqlstr &= " AND  b.Mandant='" & Mandant & "' AND b.Niederlassung='" & cboNiederlassung.Text & "' " & ""
        If cboNiederlassung.Text <> "" Then sqlstr &= " AND  b.Niederlassung=@Niederlassung " & ""

        ' sqlstr &= " AND  b.Benutzer IN (SELECT ID FROM [Personal] WHERE [Standard_RKSV_KasseId]='" & rksv_id & "')  "
        sqlstr &= " AND  b.rksv_id='" & rksv_id & "'  "

        If txtAbfertDat.Text <> "" Then
            If txtAbfertDatBis.Text <> "" Then
                sqlstr &= " AND (b.BelegDat BETWEEN @Datum_von AND @Datum_bis ) "
            Else
                sqlstr &= " AND (b.BelegDat BETWEEN @Datum_von AND @Datum_von ) "
            End If
        End If


        If txtAuftraggeberKdnr.Text <> "" And IsNumeric(txtAuftraggeberKdnr.Text) Then : sqlstr &= " AND b.[KundenNr] LIKE @VermittlerKundenNr "
        ElseIf kdtxtAuftraggeber.Text <> "" Then : sqlstr &= " AND  b.[Name1] LIKE @Vermittler " : End If

        If KdFrachtfuehrerKdnr.Text <> "" And IsNumeric(KdFrachtfuehrerKdnr.Text) Then : sqlstr &= " AND [FrachtführerKundenNr] LIKE @FrachtführerKundenNr "
        ElseIf KdFrachtfuehrer.Text <> "" Then : sqlstr &= " AND  b.[Frachtführer] LIKE @Frachtführer " : End If


        If txtAbfertigungsnummer.Text <> "" Then
            If txtAbfertigungsnummerBis.Text <> "" Then
                sqlstr &= " AND (b.[AbfertigungsNr] BETWEEN @AbfertigungsNr AND @AbfertigungsNr_bis) "
            Else
                sqlstr &= " AND b.AbfertigungsNr LIKE @AbfertigungsNr "
            End If
        End If
        If txtUnterNr.Text <> "" Then sqlstr &= " AND b.[UnterNr] LIKE @UnterNr "
        If cboFiliale._value <> "" Then sqlstr &= " AND b.[FilialenNr] LIKE @FilialenNr "
        If cboKassier._value <> "" Then sqlstr &= " AND b.[Benutzer] = @Benutzer "

        If txtLKWKennzeichen.Text <> "" Then sqlstr &= " AND b.[LKW Kennzeichen] LIKE @LKW "

        ' If txtSachbearbeiter.Text <> "" Then sqlstr &= " AND b.[Sachbearbeiter] = @Sachbearbeiter "

        If cboPreisliste._value <> "" Then sqlstr &= "  AND (SELECT COUNT(*) FROM tblEABelegposition WHERE b.BelegNr = tblEABelegposition.BelegNr AND b.BelegDat = tblEABelegposition.BelegDat AND b.Benutzer = tblEABelegposition.Benutzer AND b.Niederlassung = tblEABelegposition.Niederlassung AND b.Mandant = tblEABelegposition.Mandant  AND tblEABelegposition.[PreislistenNr] LIKE @PreislistenNr )>0  "

        Dim leistungsNr = getValues()
        If leistungsNr <> "" Then sqlstr &= " AND (SELECT COUNT(*) FROM tblEABelegposition WHERE b.BelegNr = tblEABelegposition.BelegNr AND b.BelegDat = tblEABelegposition.BelegDat AND b.Benutzer = tblEABelegposition.Benutzer AND b.Niederlassung = tblEABelegposition.Niederlassung AND b.Mandant = tblEABelegposition.Mandant  AND LeistungsNr IN (" & getValues() & "))>0 "

        Return sqlstr
    End Function


    Function getBelegList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)

        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Datum_von", txtAbfertDat.Text & " 00:00:00"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Datum_bis", txtAbfertDatBis.Text & " 23:59:59"))

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Vermittler", kdtxtAuftraggeber.Text.Replace("*", "%")))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("VermittlerKundenNr", txtAuftraggeberKdnr.Text.Replace("*", "%")))

        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("FrachtführerKundenNr", KdFrachtfuehrerKdnr.Text.Replace("*", "%")))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Frachtführer", KdFrachtfuehrer.Text.Replace("*", "%")))

        If txtAbfertigungsnummerBis.Text <> "" Then
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("AbfertigungsNr", txtAbfertigungsnummer.Text.Replace("*", "")))
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("AbfertigungsNr_bis", txtAbfertigungsnummerBis.Text.Replace("*", "")))
        Else
            list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("AbfertigungsNr", txtAbfertigungsnummer.Text.Replace("*", "%")))
        End If
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("UnterNr", txtUnterNr.Text))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("FilialenNr", cboFiliale._value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Benutzer", cboKassier._value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("LKW", txtLKWKennzeichen.Text.Replace("*", "%").ToUpper))
        ' list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Sachbearbeiter", txtSachbearbeiter.Text))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("PreislistenNr", cboPreisliste._value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Niederlassung", cboNiederlassung.Text))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Zahlungsmittel", cbxZahlungsmittel._value))

        Return list

    End Function


    Private Sub frmSpeditionsbuchSuche_Load(sender As Object, e As EventArgs) Handles Me.Load
        Me.Height = Screen.FromRectangle(Me.Bounds).WorkingArea.Size.Height
        Me.Top = 0

        txtAbfertDat.Text = Now.ToShortDateString 'CDate("01." & Now.ToString("MM.yyyy")).AddMonths(-1).ToShortDateString
        txtAbfertDatBis.Text = Now.ToShortDateString

        btnMonat.Text = MONAT.ToString("MMMM")
        btnJahr.Text = JAHR.Year

        '  kdtxtAbsender.initKdBox(Me, txtAbsenderKdnr) '   initKdAbsender()
        '  kdtxtEmpfaenger.initKdBox(Me, txtEmpfaengerKdnr) 'initKdEmpfaenger()
        kdtxtAuftraggeber.initKdBox(Me, txtAuftraggeberKdnr) 'initKdAuftraggeber()

        '  cboBerichtRgAbfArt.fillWithSQL(" SELECT [Abfertigungsart],[Abfertigungsbezeichnung] FROM [Abfertigungsarten] ORDER BY Abfertigungsart ", True, "FMZOLL", True)
        ' cboSachbearbeiter.fillWithSQL("SELECT  ID, Name FROM Personal WHERE [Status]<>'L' ORDER BY Name ", True, "FMZOLL", True)
        '     cboSachbearbeiter.fillWithSQL("SELECT  ID,/*cast(ID as nvarchar(3)) +' ' + Name as*/ Name FROM Personal WHERE [Status]<>'L' ORDER BY Name ", False, "FMZOLL", True)
        cboFiliale.fillWithSQL("SELECT FilialenNr, Grenzstelle FROM Filialen WHERE Fil_Status='A' ORDER BY FilialenNr ", True, "FMZOLL", True)
        'ComboBox1.fillWithSQL("SELECT [Abfertigungsart],[Abfertigungsbezeichnung]  FROM [Abfertigungsarten] ORDER BY Abfertigungsart ", True, "FMZOLL")
        Button4.PerformClick()



        cboKasse.fillWithSQL("SELECT [rksv_id],[rksv_bez] FROM [tblRKSV_Kassen] ", False, "FMZOLL", False)
        MyComboBox1.fillWithSQL("SELECT [rksv_id],[rksv_bez] FROM [tblRKSV_Kassen] ", False, "FMZOLL", True)
        cboKasse.changeItem(1)

        cboPreisliste.fillWithSQL("SELECT [PreislistenNr],[PreislistenBez]  FROM [tblPreislisten] ORDER BY PreislistenBez ", False, "FMZOLL", True)
        ' cboStatistik_Preisliste.fillWithSQL("SELECT [PreislistenNr],[PreislistenBez]  FROM [tblPreislisten] ORDER BY PreislistenBez ", False, "FMZOLL", True)

        cbxZahlungsmittel.fillWithSQL("SELECT distinct([Finanzwege])  FROM [tblKassenbuch] where isnull(Finanzwege,'') <> ''  ORDER BY Finanzwege ", False, "FMZOLL", True)


        If VERAG_PROG_ALLGEMEIN.cBerechtignunen.CHECK_BERECHTIGUNG_bool("ADMIN", Me) Then
            ' btnQSAufteilung.Visible = True
        End If

        btnDGVBelege.PerformClick()
    End Sub
    Function getValues() As String
        Dim s As String = ""
        For Each i In MyListBox1.SelectedItems
            s += DirectCast(i, VERAG_PROG_ALLGEMEIN.MyListItem).Value & ", "
        Next
        If s.EndsWith(", ") Then
            s = s.Substring(0, s.Length - 2)
        End If
        Return s
    End Function
    ' Private Sub Button1_Click(sender As Object, e As EventArgs)
    '      For i = 0 To MyListBox1.Items.Count - 1
    '          MyListBox1.SetSelected(i, True)
    '      Next
    'End Sub
    '

    Private Sub DataGridView2_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView.CellDoubleClick
        Try

            If e.RowIndex >= 0 Then
                Dim r As DataGridViewRow = DataGridView.Rows(e.RowIndex)

                Dim PersonalTmp = (New FMZOLL_SQL).getPersonalById(r.Cells("Benutzer").Value)

                Dim B As New EABeleg("LOAD", PersonalTmp.Mandant, PersonalTmp.Niederlassung, PersonalTmp.ID, r.Cells("BelegNr").Value, r.Cells("BelegDat").Value)
                openBELEG(B, PersonalTmp)

            End If

        Catch ex As Exception

        End Try
    End Sub
    Sub openBELEG(B As EABeleg, PERSONAL As cPersonal)
        If B Is Nothing Then Exit Sub
        Select Case B.Beleg_TYP
            Case "0"
                MsgBox("Ein NULL-Beleg ist nur einmal verfügbar.")
            Case "E"
                'If B.storniert Then MsgBox("Der Beleg wurde bereits storiniert!") : Exit Sub
                Dim frmBeleg As New frmFremdbeleg(PERSONAL, PERSONAL.Mandant, PERSONAL.Niederlassung, B.Benutzer, B.BelegNr, B.BelegDat)
                frmBeleg.ShowDialog(Me)
            Case "L"
                If B.storniert Then MsgBox("Der Beleg wurde bereits storiniert!") : Exit Sub
                Dim frmBeleg As New frmNacherfassungLeihgeld(PERSONAL, Nothing, PERSONAL.Mandant, PERSONAL.Niederlassung, B.Benutzer, B.BelegNr, B.BelegDat)
                frmBeleg.ShowDialog(Me)
            Case Else
                Dim frmBeleg As New frmBelegNeu(PERSONAL, Nothing, PERSONAL.Mandant, PERSONAL.Niederlassung, B.Benutzer, B.BelegNr, B.BelegDat)
                frmBeleg.ShowDialog(Me)
        End Select

        '  btnSuche.PerformClick()

        '  End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        For i = 0 To MyListBox1.Items.Count - 1
            MyListBox1.SetSelected(i, False)
        Next
    End Sub
    '   Sub initKdAuftraggeber()
    '     Dim dgvFindKD As New DataGridView
    ' dgvFindKD.Name = "dgvFindKD"
    ' Me.Controls.Add(dgvFindKD)
    ' dgvFindKD.Visible = False
    ' kdtxtAuftraggeber.dgv = dgvFindKD
    ' AddHandler kdtxtAuftraggeber.PropertyChanged, Sub()
    ' txtAuftraggeberKdnr.Text = IIf(kdtxtAuftraggeber.KdNr_value > 0, kdtxtAuftraggeber.KdNr_value, "")
    ' End Sub
    ' End Sub

    ' Sub initKdAbsender()
    '     Dim dgvFindKD As New DataGridView
    ' dgvFindKD.Name = "dgvFindKD"
    ' Me.Controls.Add(dgvFindKD)
    ' dgvFindKD.Visible = False
    ' kdtxtAbsender.dgv = dgvFindKD
    ' kdtxtAbsender.kdNrField = txtAbsenderKdnr
    ' End Sub

    ' Sub initKdEmpfaenger()
    '     Dim dgvFindKD As New DataGridView
    ' dgvFindKD.Name = "dgvFindKD"
    ' Me.Controls.Add(dgvFindKD)
    ' dgvFindKD.Visible = False
    ' kdtxtEmpfaenger.dgv = dgvFindKD
    ' kdtxtEmpfaenger.kdNrField = txtEmpfaengerKdnr
    ' End Sub

    ' Sub initKdFrachtfuehrer()
    '     Dim dgvFindKD As New DataGridView
    ' dgvFindKD.Name = "dgvFindKD"
    ' Me.Controls.Add(dgvFindKD)
    ' dgvFindKD.Visible = False
    ' kdtxtFrachtfuehrer.dgv = dgvFindKD
    ' kdtxtFrachtfuehrer.kdNrField = txtFrachtfuehrerKdnr
    ' End Sub

    ' Sub initKdEndempfaenger()
    '     Dim dgvFindKD As New DataGridView
    ' dgvFindKD.Name = "dgvFindKD"
    ' Me.Controls.Add(dgvFindKD)
    ' dgvFindKD.Visible = False
    ' kdtxtEndempfaenger.dgv = dgvFindKD
    ' kdtxtEndempfaenger.kdNrField = txtEndempfaengerKdnr
    ' End Sub


    Private Sub txtAbfertDat_TextChanged(sender As Object, e As EventArgs) Handles txtAbfertDat.TextChanged
        txtAbfertDatBis.Enabled = sender.text <> ""
    End Sub

    Private Sub MyTextBox1_TextChanged(sender As Object, e As EventArgs) Handles txtAbfertigungsnummer.TextChanged
        txtAbfertigungsnummerBis.Enabled = sender.text <> ""
    End Sub

    Private Sub DataGridView_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView.CellMouseClick
        If e.Button = Windows.Forms.MouseButtons.Right Then
            DataGridView.ClearSelection()
            DataGridView.Rows(e.RowIndex).Selected = True
        End If
    End Sub


    Private Sub Button1_Click_1(sender As Object, e As EventArgs)
        Dim frmNacherfassung As New frmNacherfassungNEU
        ' frmNacherfassung.cboFiliale.Text = DataGridView.SelectedRows(0).Cells("FilialenNr").Value
        ' frmNacherfassung.txtUnterNr.Text = DataGridView.SelectedRows(0).Cells("UnterNr").Value
        ' frmNacherfassung.txtAbfertigungsnummer.Text = DataGridView.SelectedRows(0).Cells("AbfertigungsNr").Value
        frmNacherfassung.newEntry = True
        '  frmNacherfassung.FMZollPersID = VERAG_PROG_ALLGEMEIN.cglobal.AktiverMitarbeiter.mit_FMZollPersID
        ' frmNacherfassung.initDataBinding()
        frmNacherfassung.ShowDialog(Me)
        DataGridView.RELOAD()
    End Sub

    Private Sub EintragLöschenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles EintragLöschenToolStripMenuItem.Click
        If DataGridView.SelectedRows.Count > 0 Then
            If vbYes = MsgBox("Möchten Sie den Eintrag wirklich löschen?", vbYesNoCancel) Then
                Dim r As DataGridViewRow = DataGridView.SelectedRows(0)
                SQL.doSQL("DELETE FROM [Speditionsbuch] WHERE [FilialenNr]='" & r.Cells("FilialenNr").Value & "' AND [AbfertigungsNr] ='" & r.Cells("AbfertigungsNr").Value & "' AND [UnterNr]='" & r.Cells("UnterNr").Value & "' ", "FMZOLL")
                DataGridView.RELOAD()
            End If
        End If
    End Sub




    Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
        txtAbfertDat._value = CDate(sender.value).ToShortDateString
    End Sub

    Private Sub DateTimePicker2_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker2.ValueChanged
        txtAbfertDatBis._value = CDate(sender.value).ToShortDateString
    End Sub

    Private Sub btnMonat_Click(sender As Object, e As EventArgs) Handles btnMonat.Click
        initBtns("Monat")
    End Sub

    Dim MONAT As Date = CDate("01." & Now.Month & "." & Now.Year) '.AddMonths(-1)
    Dim srcTAG As Date = CDate(Now.ToShortDateString)

    Dim JAHR As Date = CDate("01.01." & Now.Year)

    Sub initBtns(MonatJahr)
        btnMonat.Text = MONAT.ToString("MMMM")
        btnJahr.Text = JAHR.Year
        Select Case MonatJahr
            Case "Monat"
                DateTimePicker1.Value = MONAT
                DateTimePicker2.Value = MONAT.AddMonths(1).AddDays(-1)
            Case "Jahr"
                '  If cbxGeschaftsjahr.Checked Then
                'DateTimePicker1.Value = JAHR.AddMonths(1)
                ' DateTimePicker2.Value = JAHR.AddYears(1).AddMonths(1).AddDays(-1)
                ' Else
                DateTimePicker1.Value = JAHR
                DateTimePicker2.Value = JAHR.AddYears(1).AddDays(-1)
                'End If
            Case "Tag"
                '  If cbxGeschaftsjahr.Checked Then
                'DateTimePicker1.Value = JAHR.AddMonths(1)
                ' DateTimePicker2.Value = JAHR.AddYears(1).AddMonths(1).AddDays(-1)
                ' Else
                DateTimePicker1.Value = srcTAG
                DateTimePicker2.Value = srcTAG
                If srcTAG = Now.ToShortDateString Then
                    Button5.Text = "Heute"
                ElseIf srcTAG = Now.AddDays(-1).ToShortDateString Then
                    Button5.Text = "Gestern"
                ElseIf srcTAG = Now.AddDays(-2).ToShortDateString Then
                    Button5.Text = "Vorgestern"
                Else
                    Button5.Text = srcTAG.ToString("dd.MM")
                End If

                'End If
            Case ""
                DateTimePicker1.Value = ("01." & Now.Month & "." & Now.Year)
                DateTimePicker2.Value = Now
        End Select

    End Sub

    Private Sub btnJahr_Click(sender As Object, e As EventArgs) Handles btnJahr.Click
        initBtns("Jahr")
    End Sub

    Private Sub btnBisMonat_Click(sender As Object, e As EventArgs) Handles btnBisMonat.Click
        MONAT = MONAT.AddMonths(1)
        initBtns("Monat")
    End Sub

    Private Sub btnVonMonat_Click(sender As Object, e As EventArgs) Handles btnVonMonat.Click
        MONAT = MONAT.AddMonths(-1)
        initBtns("Monat")
    End Sub

    Private Sub btnBisJahr_Click(sender As Object, e As EventArgs) Handles btnBisJahr.Click
        JAHR = JAHR.AddYears(1)
        initBtns("Jahr")
    End Sub

    Private Sub btnVonJahr_Click(sender As Object, e As EventArgs) Handles btnVonJahr.Click
        JAHR = JAHR.AddYears(-1)
        initBtns("Jahr")
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        SplitContainer1.Panel2Collapsed = Not SplitContainer1.Panel2Collapsed

        If SplitContainer1.Panel2Collapsed Then
            '    pnlSearch.Height = SplitContainer1.Panel1.Height
            SplitContainer.SplitterDistance -= 150
        Else
            'pnlSearch.Height = SplitContainer1.Height
            SplitContainer.SplitterDistance += 150
        End If

        If Button4.Image Is SDL.My.Resources.Resources.pfeil_unten Then
            Button4.Image = SDL.My.Resources.Resources.pfeil_oben
        Else
            Button4.Image = SDL.My.Resources.Resources.pfeil_unten
        End If
    End Sub


    Private Sub FlatButton7_Click(sender As Object, e As EventArgs) Handles FlatButton7.Click
        DataGridView.RELOAD()
    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        srcTAG = srcTAG.AddDays(-1)
        initBtns("Tag")
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        srcTAG = srcTAG.AddDays(1)
        initBtns("Tag")
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        initBtns("Tag")
    End Sub

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

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

        Dim displayFilter = False




        Dim print As New frmPrintLayout
        print.Text = "Kassenbericht"

        Dim rpt As New rptKassenbuchBericht

        rpt.DataSource = SQL.loadDgvBySql_Param("SELECT  b.BelegDat,b.rksv_BelegId,case when (b.FilialenNr<=0 OR b.AbfertigungsNr<=0)  THEN p.FilialenNr ELSE b.FilialenNr END as FilialenNr,case when (b.FilialenNr<=0 OR b.AbfertigungsNr<=0) THEN p.AbfertigungsNr ELSE b.AbfertigungsNr END as AbfertigungsNr,b.Name1,b.Frachtführer,b.[LKW Kennzeichen],p.Anzahl,p.LeistungsNr,p.LeistungsBez,p.Leistungsbeschreibung,p.Preis,p.Betrag,b.LKW_Id FROM [tblEABelegnummer] as b INNER JOIN [tblEABelegposition] as p ON  (b.BelegNr = p.BelegNr AND b.BelegDat = p.BelegDat AND b.Benutzer = p.Benutzer AND b.Niederlassung = p.Niederlassung AND b.Mandant = p.Mandant) " &
                         " WHERE 1=1 " & getBelegWhere() & " ORDER BY " & If(cbxStat_Filiale.Checked, "FilialenNr,", "") & " " & If(cbxStat_Leistung.Checked, "p.LeistungsNr,", "") & " b.[Mandant],b.[Niederlassung],b.[BelegDat],[rksv_id],[rksv_BelegId]", "FMZOLL", , getBelegList)

        If rpt.DataSource Is Nothing Then
            MsgBox("Keine Daten!")
            Exit Sub
        End If

         

        'Filter anzeigen
        '  If displayFilter Then
        '        rpt.lblFilterTxt.Visible = displayFilter
        'rpt.txtFilter.Visible = displayFilter
        'rpt.txtFilter.Text = SQL.getStringReplaceScalarVar(getSpedBuchWhere, getSpedbuchList)
        'Else
        'If txtUeberschr.Text <> "" Then
        '        rpt.txtFilter.Text = txtUeberschr.Text
        'rpt.txtFilter.Visible = True
        'rpt.lblFilterTxt.Visible = True
        'rpt.lblFilterTxt.Text = "Beschreibung:"
        'End If
        'End If



        If cbxStat_Filiale.Checked Then rpt.GroupHeader1.DataField = "FilialenNr" 'Gruppierung

        If cbxStat_Leistung.Checked Then rpt.GroupHeader2.DataField = "LeistungsNr" 'Gruppierung



        ' rpt.GroupHeader2.DataField = "AvisoId" 'Gruppierung

        ' MsgBox(rpt.DataSource.rows.count)

        If DirectCast(rpt.DataSource, DataTable).Rows.Count = 0 Then
            rpt.Dispose() : print.Dispose()
            MsgBox("Keine Daten vorhanden!")
            Exit Sub
        End If

        If cboKassier._value <> "" Then
            rpt.lblFilterTxt.Text = "Kassier: " & cboKassier.Text
            rpt.lblFilterTxt.Visible = True
        End If


        Dim sum = 0
        rpt.lblUeberschrift.Text = "Kassenbericht  " & txtAbfertDat.Text & " bis " & txtAbfertDatBis.Text
        rpt.lblSachbearbeiter.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME
        'rpt.lblMandantNiederlassung.Text = PERSONAL.Mandant & "  /  " & PERSONAL.Niederlassung

        'Dim cnt As Integer = 0
        rpt.lblDat.Text = Now.ToLongDateString
        Dim sumBtr As Double = 0
        Dim sumEp As Double = 0
        Dim gesSumBtr As Double = 0
        Dim gesSumEp As Double = 0
        Dim gesgesSumBtr As Double = 0
        Dim gesgesSumEp As Double = 0
        Dim gesgesSumAnz = 0
        Dim gesSumAnz = 0
        Dim belegId As String = ""



        AddHandler rpt.Detail.Format, Sub()
                                          If belegId = rpt.Fields.Item("rksv_BelegId").Value.ToString Then ' Selber Beleg, andere BelegPosition
                                              rpt.lblBelegDatum.Visible = False
                                              rpt.lblBelegNr.Visible = False
                                              ' rpt.lblFilialeAbfertigungNr.Visible = False
                                              rpt.lblAuftraggeber.Visible = False
                                              rpt.lblRechnungAn.Visible = False
                                              rpt.lblLkw.Visible = False
                                          Else
                                              rpt.lblBelegDatum.Visible = True
                                              rpt.lblBelegNr.Visible = True
                                              rpt.lblFilialeAbfertigungNr.Visible = True
                                              rpt.lblAuftraggeber.Visible = True
                                              rpt.lblRechnungAn.Visible = True
                                              rpt.lblLkw.Visible = True
                                              belegId = rpt.Fields.Item("rksv_BelegId").Value.ToString
                                          End If

                                          rpt.lblBelegDatum.Text = rpt.Fields.Item("BelegDat").Value
                                          rpt.lblBelegNr.Text = rpt.Fields.Item("rksv_BelegId").Value

                                          rpt.lblFilialeAbfertigungNr.Text = rpt.Fields.Item("FilialenNr").Value & "/" & rpt.Fields.Item("AbfertigungsNr").Value
                                          If rpt.lblFilialeAbfertigungNr.Text = "0/0" Or rpt.lblFilialeAbfertigungNr.Text = "-1/-1" Then
                                              If rpt.Fields.Item("LKW_Id").Value IsNot DBNull.Value Then
                                                  rpt.lblFilialeAbfertigungNr.Text = "LKW: " & rpt.Fields.Item("LKW_Id").Value
                                              Else
                                                  rpt.lblFilialeAbfertigungNr.Text = "-"
                                              End If
                                          End If
                                          rpt.lblAuftraggeber.Text = rpt.Fields.Item("Name1").Value
                                          rpt.lblRechnungAn.Text = rpt.Fields.Item("Frachtführer").Value
                                          rpt.lblLkw.Text = rpt.Fields.Item("LKW Kennzeichen").Value

                                          rpt.lblAnzahl.Text = rpt.Fields.Item("Anzahl").Value
                                          rpt.lblLeistung.Text = rpt.Fields.Item("Leistungsbeschreibung").Value
                                          '    rpt.lblLeistungnr.Text = rpt.Fields.Item("LeistungsNr").Value

                                          Dim ep As Double = 0
                                          Dim btr As Double = 0

                                          If IsNumeric(checkNull(rpt.Fields.Item("Preis").Value)) Then ep = CDbl(rpt.Fields.Item("Preis").Value())
                                          rpt.lblEPBetragEUR.Text = CDbl(ep).ToString("N2", Globalization.CultureInfo.CurrentCulture)

                                          If IsNumeric(checkNull(rpt.Fields.Item("Betrag").Value)) Then btr = CDbl(rpt.Fields.Item("Betrag").Value())
                                          rpt.lblBetragEUR.Text = CDbl(btr).ToString("N2", Globalization.CultureInfo.CurrentCulture)


                                          sumBtr += btr
                                          sumEp += ep

                                          gesSumBtr += btr
                                          gesSumEp += ep

                                          gesgesSumBtr += btr
                                          gesgesSumEp += ep

                                          gesSumAnz += 1
                                          gesgesSumAnz += 1

                                      End Sub
        AddHandler rpt.GroupHeader1.Format, Sub()
                                                rpt.lblFiskalvertretung.Text = "Filiale " & checkNull(rpt.Fields.Item("FilialenNr").Value) & " - " & SQL.getValueTxtBySql("SELECT TOP 1 [Grenzstelle] FROM [Filialen] where FilialenNr='" & checkNull(rpt.Fields.Item("FilialenNr").Value) & "'", "FMZOLL")
                                                rpt.lblFiskalvertretungLand.Text = checkNull(rpt.Fields.Item("FilialenNr").Value)

                                                gesSumBtr = 0
                                                gesSumEp = 0
                                                gesSumAnz = 0
                                                rpt.lblGesSumTxt.Text = "Summe " & checkNull(rpt.Fields.Item("FilialenNr").Value) & ":"
                                            End Sub
        AddHandler rpt.GroupHeader2.Format, Sub()
                                                rpt.lblUIDNr.Text = checkNull(rpt.Fields.Item("LeistungsNr").Value) & " - " & checkNull(rpt.Fields.Item("LeistungsBez").Value)

                                                sumBtr = 0
                                                sumEp = 0

                                            End Sub

        AddHandler rpt.GroupFooter2.Format, Sub()
                                                'rpt.lblSumAbfertigungsart.Text = sumAbfBez
                                                'rpt.lblSumBarzahlungsbetrag.Text = sumBar.ToString("N2", CultureInfo.CurrentCulture)
                                                'rpt.lblSumRechnungsbetrag.Text = sumRg.ToString("N2", CultureInfo.CurrentCulture)
                                                'rpt.lblSumAnzahl.Text = sumAnz.ToString("N0")
                                                'rpt.lblSuag.Text = sumRg.ToString("C")
                                                rpt.lblSumRe.Text = sumEp.ToString("N2", CultureInfo.CurrentCulture)
                                                rpt.lblSumEust.Text = sumBtr.ToString("N2", CultureInfo.CurrentCulture)


                                            End Sub

        AddHandler rpt.GroupFooter1.Format, Sub()
                                                rpt.lblGesSumRe.Text = gesSumEp.ToString("N2", CultureInfo.CurrentCulture)
                                                rpt.lblGesSumEust.Text = gesSumBtr.ToString("N2", CultureInfo.CurrentCulture)
                                                rpt.lblGesSumAnzahl.Text = gesSumAnz.ToString("N0")

                                            End Sub
        AddHandler rpt.ReportFooter1.Format, Sub()

                                                 rpt.lblGesgesSumRe.Text = gesgesSumEp.ToString("N2", CultureInfo.CurrentCulture)
                                                 rpt.lblGesgesSumEust.Text = gesgesSumBtr.ToString("N2", CultureInfo.CurrentCulture)
                                                 rpt.lblGesGesSumAnzahl.Text = gesgesSumAnz.ToString("N0")

                                             End Sub

        print.Viewer.LoadDocument(rpt)
        print.Viewer.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
        print.Show()

    End Sub

    Function checkNull(o As Object, Optional ret As String = "") As Object
        If o Is Nothing Then Return ret
        If o Is DBNull.Value Then Return ret
        Return o
    End Function


    Private Sub btnEinnahmeBeleg_Click(sender As Object, e As EventArgs) Handles btnDGVBelege.Click
        DGV = "B"
        btnSuche.PerformClick()
    End Sub

    Private Sub btnAusgabebeleg_Click(sender As Object, e As EventArgs) Handles btnDGVKassenbuch.Click
        DGV = "KB"
        btnSuche.PerformClick()
    End Sub

    Private Sub cboPreisliste_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPreisliste.SelectedIndexChanged
        MyListBox1.Items.Clear()
        If IsNumeric(cboPreisliste._value) Then
            MyListBox1.fillWithSQL("SELECT Leistungen.LeistungsNr, max(Leistungen.[LeistungsBez])   " &
              " FROM [VERAG].[dbo].[tblPreislistenpositionen] inner join Leistungen on Leistungen.LeistungsNr=[tblPreislistenpositionen].LeistungsNr " &
              " where PreislistenNr=" & cboPreisliste._value & "  group by Leistungen.LeistungsNr", True, "FMZOLL")
        End If
    End Sub

    Private Sub MyComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs)
        '    MyComboBox2.Items.Clear()
        '    If IsNumeric(cboPreisliste._value) Then
        ' MyComboBox2.fillWithSQL("SELECT Leistungen.LeistungsNr, max(Leistungen.[LeistungsBez])   " &
        '   " FROM [VERAG].[dbo].[tblPreislistenpositionen] inner join Leistungen on Leistungen.LeistungsNr=[tblPreislistenpositionen].LeistungsNr " &
        '   " where PreislistenNr=" & MyComboBox2._value & "  group by Leistungen.LeistungsNr", True, "FMZOLL")
        ' End If
    End Sub

    Private Sub cboKasse_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboKasse.SelectedIndexChanged
        cboNiederlassung.Items.Clear()

        If IsNumeric(cboKasse._value) Then
            cboNiederlassung.fillWithSQL("SELECT distinct([Niederlassung]) FROM [Personal]  where Standard_RKSV_KasseId=" & cboKasse._value & " AND [Niederlassung] is not null order by [Niederlassung]", False, "FMZOLL", True)

            Select Case cboKasse._value
                Case 20
                    cboKassier.fillWithSQL("SELECT ID,[Name]  FROM [Personal]  where [Mandant]='IMEX' order by name", True, "FMZOLL", True)
                Case Else
                    cboKassier.fillWithSQL("SELECT ID,[Name]  FROM [Personal]  where [Mandant]='VERA' AND [Standard_RKSV_KasseId]='" & cboKasse._value & "' " & If(CheckBox1.Checked, "AND Status='A' AND BLC='R'", "") & " order by name", True, "FMZOLL", True)
            End Select
        End If


    End Sub

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

        Dim displayFilter = False




        Dim print As New frmPrintLayout
        print.Text = "Kassenbericht"

        Dim rpt As New rptKassenbuchBerichtSaldenBenutzer

        'If MyComboBox1._value = "" Then
        '    MsgBox("Keine Kasse!") : Exit Sub
        'End If

        Dim sqlStr = ""
        sqlStr &= " SELECT Benutzer,Name, Konto, Sum(tblKassenbuch.Soll) AS Soll, Sum(tblKassenbuch.Haben) AS Haben, (Sum(tblKassenbuch.Soll)-Sum(tblKassenbuch.Haben)) AS Saldo  "
        sqlStr &= " FROM Personal INNER JOIN tblKassenbuch ON Personal.ID = tblKassenbuch.Benutzer  "
        sqlStr &= " WHERE tblKassenbuch.Geschäftsjahr='" & cRKSV.getGJ_FIRMA(Now, VERAG_PROG_ALLGEMEIN.cAllgemein.FIRMA) & "' and konto=KassenbuchNr "
        If MyComboBox1._value <> "" Then sqlStr &= " AND rksv_id=" & MyComboBox1._value & " "
        If MyComboBox2._value <> "" Then sqlStr &= " AND tblKassenbuch.Niederlassung ='" & MyComboBox2._value & "'"
        sqlStr &= " group by Benutzer,Name, Konto order by Name"
        'cRKSV.getGJ(Now) 
        rpt.DataSource = SQL.loadDgvBySql_Param(sqlStr, "FMZOLL", , getBelegList)

        If rpt.DataSource Is Nothing Then
            MsgBox("Keine Daten!")
            Exit Sub
        End If





        If DirectCast(rpt.DataSource, DataTable).Rows.Count = 0 Then
            rpt.Dispose() : print.Dispose()
            MsgBox("Keine Daten vorhanden!")
            Exit Sub
        End If


        Dim sum = 0
        rpt.lblSachbearbeiter.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME
        'rpt.lblMandantNiederlassung.Text = PERSONAL.Mandant & "  /  " & PERSONAL.Niederlassung


        'Dim cnt As Integer = 0
        rpt.lblDat.Text = Now.ToLongDateString
        rpt.lblUeberschrift.Text = "Salden Bericht, vom " & Now.ToShortDateString
        Dim sumBtr As Double = 0


        AddHandler rpt.Detail.Format, Sub()

                                          rpt.lblKassenbuchNr.Text = rpt.Fields.Item("Konto").Value
                                          rpt.lblBenutzer.Text = rpt.Fields.Item("Name").Value
                                          rpt.lblBetragEUR.Text = CDbl(rpt.Fields.Item("Saldo").Value).ToString("N2", Globalization.CultureInfo.CurrentCulture)
                                          Try
                                              sumBtr += CDbl(rpt.Fields.Item("Saldo").Value)
                                          Catch ex As Exception

                                          End Try

                                      End Sub
        AddHandler rpt.GroupHeader1.Format, Sub()
                                                rpt.lblKasse.Text = MyComboBox1.Text

                                            End Sub


        AddHandler rpt.GroupFooter1.Format, Sub()
                                                rpt.lblGesSumEust.Text = sumBtr.ToString("N2", CultureInfo.CurrentCulture)
                                            End Sub


        print.Viewer.LoadDocument(rpt)
        print.Viewer.ViewType = GrapeCity.Viewer.Common.Model.ViewType.Continuous
        print.Show()

    End Sub

    Private Sub MyComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles MyComboBox1.SelectedIndexChanged
        cboNiederlassung.Items.Clear()

        If IsNumeric(MyComboBox1._value) Then
            MyComboBox2.fillWithSQL("SELECT distinct([Niederlassung]) FROM [Personal]  where Standard_RKSV_KasseId=" & MyComboBox1._value & " AND [Niederlassung] is not null order by [Niederlassung]", False, "FMZOLL", True)

        End If

    End Sub

    Private Sub CheckBox1_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox1.CheckedChanged
        cboKasse_SelectedIndexChanged(cboKasse, New EventArgs)
    End Sub

    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click

        Dim displayFilter = False




        Dim print As New frmPrintLayout
        print.Text = "Kassenbericht"

        Dim rpt As New rptKassenbuchBerichtSollHaben

        'If MyComboBox1._value = "" Then
        '    MsgBox("Keine Kasse!") : Exit Sub
        'End If

        Dim sqlStr = ""
        sqlStr &= " SELECT Benutzer,Name, Konto, isnull(Sum(tblKassenbuch.Soll),0) AS Soll, isnull(Sum(tblKassenbuch.Haben),0) AS Haben, (Sum(tblKassenbuch.Soll)-Sum(tblKassenbuch.Haben)) AS Saldo  "
        sqlStr &= " FROM Personal INNER JOIN tblKassenbuch ON Personal.ID = tblKassenbuch.Benutzer  "
        sqlStr &= " WHERE konto=KassenbuchNr "
        If txtAbfertDat.Text <> "" Then
            If txtAbfertDatBis.Text <> "" Then
                sqlStr &= " AND (Buchungsdatum BETWEEN @Datum_von AND @Datum_bis ) "
            Else
                sqlStr &= " AND (Buchungsdatum BETWEEN @Datum_von AND @Datum_von ) "
            End If
        End If

        If cboKasse._value <> "" Then sqlStr &= " AND rksv_id=" & cboKasse._value & " "
        If cboNiederlassung._value <> "" Then sqlStr &= " AND tblKassenbuch.Niederlassung ='" & cboNiederlassung._value & "'"
        sqlStr &= " group by Benutzer,Name, Konto order by Name"



        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Datum_von", txtAbfertDat.Text & " 00:00:00"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Datum_bis", txtAbfertDatBis.Text & " 23:59:59"))


        rpt.DataSource = SQL.loadDgvBySql_Param(sqlStr, "FMZOLL", , list)

        If rpt.DataSource Is Nothing Then
            MsgBox("Keine Daten!")
            Exit Sub
        End If



        rpt.lblUeberschrift.Text = "SOLL HABEN Bericht von " & txtAbfertDat.Text & " bis " & txtAbfertDatBis.Text

        If DirectCast(rpt.DataSource, DataTable).Rows.Count = 0 Then
            rpt.Dispose() : print.Dispose()
            MsgBox("Keine Daten vorhanden!")
            Exit Sub
        End If


        Dim sum = 0
        rpt.lblSachbearbeiter.Text = VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME
        'rpt.lblMandantNiederlassung.Text = PERSONAL.Mandant & "  /  " & PERSONAL.Niederlassung


        'Dim cnt As Integer = 0
        rpt.lblDat.Text = Now.ToLongDateString
        Dim sumBtrSoll As Double = 0
        Dim sumBtrHaben As Double = 0


        AddHandler rpt.Detail.Format, Sub()

                                          rpt.lblKassenbuchNr.Text = rpt.Fields.Item("Konto").Value
                                          rpt.lblBenutzer.Text = rpt.Fields.Item("Name").Value
                                          rpt.lblBetragSoll.Text = CDbl(rpt.Fields.Item("Soll").Value).ToString("N2", Globalization.CultureInfo.CurrentCulture)
                                          rpt.lblBetragHaben.Text = CDbl(rpt.Fields.Item("Haben").Value).ToString("N2", Globalization.CultureInfo.CurrentCulture)
                                          Try
                                              sumBtrSoll += CDbl(rpt.Fields.Item("Soll").Value)
                                              sumBtrHaben += CDbl(rpt.Fields.Item("Haben").Value)
                                          Catch ex As Exception

                                          End Try

                                      End Sub
        AddHandler rpt.GroupHeader1.Format, Sub()
                                                rpt.lblKasse.Text = MyComboBox1.Text

                                            End Sub


        AddHandler rpt.GroupFooter1.Format, Sub()
                                                rpt.lblGesSumSoll.Text = sumBtrSoll.ToString("N2", CultureInfo.CurrentCulture)
                                                rpt.lblGesSumHaben.Text = sumBtrHaben.ToString("N2", CultureInfo.CurrentCulture)
                                            End Sub


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