Imports DevExpress.XtraScheduler
Imports WINDREAMLib
Imports System.IO
Imports DevExpress.XtraGrid.Views.Grid
Imports System.Text
Imports DevExpress.XtraTreeList
Imports DevExpress.XtraTreeList.Nodes
Imports DevExpress.XtraEditors.Repository

Public Class frmForm_Constructor
    'Private Shared _Instance As frmForm_Constructor = Nothing
    'Public Shared Function Instance() As frmForm_Constructor
    '    If _Instance Is Nothing OrElse _Instance.IsDisposed = True Then
    '        _Instance = New frmForm_Constructor
    '    End If
    '    _Instance.BringToFront()
    '    Return _Instance
    'End Function
#Region "+++++ Konstanten und Variablen +++++"
    Private CONSTRUCTORID As Integer
    'Private akt_ctrl As Control
    Private FORM1_ID As Integer = Nothing
    Private ACT_EBENE As Integer = 0
    Private ACT_EBENE_STRING As String = ""


    Private EBENE1_ENTITY As String = Nothing
    Private EBENE1_COLUMNNAME As String = Nothing
    Private EBENE1_GRID_RESULT As String = Nothing
    Private EBENE1_RECID As Integer = 0

    Private EBENE2_PARENT_ID As Integer = 0
    Private EBENE2_ENTITY As String = Nothing
    Private EBENE2_COLUMNNAME As String = Nothing
    Private EBENE2_GRID_RESULT As String = Nothing
    Private EBENE2_RECID As Integer = 0

    Private EBENE3_PARENT_ID As Integer = 0
    Private EBENE3_ENTITY As String = Nothing
    Private EBENE3_COLUMNNAME As String = Nothing
    Private EBENE3_GRID_RESULT As String = Nothing
    Private EBENE3_RECID As Integer = 0
    Private EBENE_SQLRESULT As String

    Private DT_CONSTRUCT_VIEW As DataTable

    Private DT_SELECTION As DataTable
    Private thisFORMVIEW_ID As Integer
    Private _windream As New ClassWindream
    Private SelectedRecordID As Integer
    Private EDIT_STATE As String = "none"
    Private RECORD_CHANGED As Boolean = False
    Private RECORD_NEEDS_REFRESH As Boolean = False

    Private act_ParentEntity_String As String
    Private act_PKEntity_String As String
    'Private act_ParentGridView As DevExpress.XtraGrid.Views.Grid.GridView
    ' Private act_GridView As DevExpress.XtraGrid.Views.Grid.GridView
    Private act_FormViewID As Integer


    Private Record1_ID As Integer
    Private Record2_ID As Integer
    Private Record3_ID As Integer
    Private insert = False
    Private windream_Docshow As Boolean = False
    Private FOLLOW_UPisActive As Boolean = False
    Private WD_Suche As String
    Private SP1 As String
    Private SP2 As String
    Private SP3 As String
    Private SP4 As String
    Private SP5 As String
    Private FormLoaded As Boolean = False
    Private vFormClosing As Boolean = False
    Private dataloaded As Boolean = False
    Private SaveRoutine_Active As Boolean = False

    Public Shared windream_temp_search

    Private CheckBoxEditorForDisplay As RepositoryItemCheckEdit
    Private DocView
    Private OpenedFileString As String
    Private DocViewString As String

    Private DT_FU_Record As DataTable
    Private DT_FU_ENTITY As DataTable
    Private FOLL_UP_RECORD_DEFINED As Boolean = False
    Private FOLL_UP_DATE_CTRL_ID As Integer
    Private FOLL_UP_DONE_CTRL_ID As Integer
    Private FOLL_UP_ID As Integer
    'Private Shared _Instance As frmFormInput = Nothing
    'Public Shared Function Instance() As frmForm_Constructor
    '    If _Instance Is Nothing OrElse _Instance.IsDisposed = True Then
    '        _Instance = New frmForm_Constructor
    '    End If
    '    _Instance.BringToFront()
    '    Return _Instance
    'End Function

#End Region
#Region "+++++ Mouse/Key Events +++++"

    Private Sub frmForm_Constructor_HandleDestroyed(sender As Object, e As EventArgs) Handles Me.HandleDestroyed

    End Sub
    Private Sub Control_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseDown

    End Sub
    Private Sub Control_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Me.MouseUp

    End Sub
    Private Sub Control_MouseMove(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseMove

    End Sub
    Private Sub frmForm_Constructor_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        vFormClosing = True
        Check_Record_Changed()
        SaveLayout()
        CloseWDDocview()
        ClassWindowLocation.SaveFormLocationSize(Me, CONSTRUCTORID, CURRENT_SCREEN_ID, "CONSTRUCTOR")
    End Sub

#End Region
    Private Sub SaveLayout()
        Try
            Dim LayoutPath = Path.Combine(Application.UserAppDataPath(), "FORM_CONSTRUCT-Splitter-" & CONSTRUCTORID & "-UserLayout.xml")

            Dim layout As ClassLayout = New ClassLayout(LayoutPath)
            Dim settings As System.Collections.Generic.List(Of ClassSetting) = New System.Collections.Generic.List(Of ClassSetting)
            'settings.Add(New ClassSetting("SplitContainerDetails", SplitContainerDetails.SplitterPosition))
            ' settings.Add(New ClassSetting("SplitContainerControlDetails1", SplitContainerControlDetails.SplitterPosition))
            settings.Add(New ClassSetting("SplitContainerMain", SplitContainerMain.SplitterDistance))
            settings.Add(New ClassSetting("TreeViewEbeneSelect", TreeViewEbeneSelect.Size.ToString))
            'settings.Add(New ClassSetting("GroupControlSelection", GroupControlSelection.Size.ToString))
            layout.Save(settings)

        Catch ex As Exception
            MsgBox("Error while saving custom Layout:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub LoadLayouts()
        Try
            Dim LayoutPath = Path.Combine(Application.UserAppDataPath(), "FORM_CONSTRUCT-Splitter-" & CONSTRUCTORID & "-UserLayout.xml")

            Dim layout As ClassLayout = New ClassLayout(LayoutPath)
            Dim settings As System.Collections.Generic.List(Of ClassSetting)
            settings = layout.Load()

            If settings.Count = 0 Then
                'settings.Add(New ClassSetting("SplitContainerDetails", SplitContainerDetails.SplitterPosition))
                'settings.Add(New ClassSetting("SplitContainerControlDetails1", SplitContainerControlDetails.SplitterPosition))
                settings.Add(New ClassSetting("SplitContainerMain", SplitContainerMain.SplitterDistance))
                settings.Add(New ClassSetting("TreeViewEbeneSelect", TreeViewEbeneSelect.Size.ToString))
                'settings.Add(New ClassSetting("GroupControlSelection", GroupControlSelection.Size.ToString))
                layout.Save(settings)
            End If

            For Each s As ClassSetting In settings
                Select Case s._name
                    Case "SplitContainerDetails"
                        ' SplitContainerDetails.SplitterPosition = Integer.Parse(s._value)
                    Case "SplitContainerControlDetails1"
                        '  SplitContainerControlDetails.SplitterPosition = Integer.Parse(s._value)
                    Case "SplitContainerMain"
                        SplitContainerMain.SplitterDistance = Integer.Parse(s._value)
                    Case "TreeViewEbeneSelect"
                        Dim result() As String
                        result = s._value.Split(",")
                        Dim width As Integer
                        Dim height As Integer
                        For Each f As String In result
                            If f.Contains("{Width=") Then
                                Dim res = f.Replace("{Width=", "")
                                width = CInt(res)
                            Else
                                Dim res = f.Replace(" Height=", "")
                                res = res.Replace("}", "")
                                height = CInt(res)
                            End If
                        Next
                        TreeViewEbeneSelect.Size = New System.Drawing.Size(width, height)
                    Case "GroupControlSelection"
                        Dim result() As String
                        result = s._value.Split(",")
                        Dim width As Integer
                        Dim height As Integer
                        For Each f As String In result
                            If f.Contains("{Width=") Then
                                Dim res = f.Replace("{Width=", "")
                                width = CInt(res)
                            Else
                                Dim res = f.Replace(" Height=", "")
                                res = res.Replace("}", "")
                                height = CInt(res)
                            End If
                        Next
                        'GroupControlSelection.Size = New System.Drawing.Size(width, height)

                End Select
            Next
            'MsgBox(My.Settings.OV_Position)
            'Me.Location = New Point(My.Settings.OV_Position)
            'MsgBox(My.Settings.OV1_SEebene1_SD)
            ' SplitContainerControlDetails1.SplitterPosition = My.Settings.OV1_SCDetails1
        Catch notFoundEx As System.IO.FileNotFoundException
            MsgBox("Datagridview-Layout could not be loaded. Layout will be saved after closing", MsgBoxStyle.Information)

        Catch ex As Exception
            MsgBox("Error while loading custom Layout!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub frmForm_Constructor_Load(sender As Object, e As EventArgs) Handles Me.Load
        Try
            Me.Cursor = Cursors.WaitCursor
            SplitCont_Details.Collapsed = True
            CONSTRUCTORID = CURRENT_CONSTRUCTOR_ID
            ClassWindowLocation.LoadFormLocationSize(Me, CONSTRUCTORID, CURRENT_SCREEN_ID, "CONSTRUCTOR")
            VWPMO_WF_USER_ACTIVETableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBPMO_FILES_USERTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.VWPMO_WF_ACTIVETableAdapter.Connection.ConnectionString = MyConnectionString
            DT_CONSTRUCT_VIEW = ClassDatabase.Return_Datatable("SELECT * FROM TBPMO_FORM_CONSTRUCTOR WHERE GUID = " & CONSTRUCTORID)
            If DT_CONSTRUCT_VIEW.Rows.Count = 1 Then
                'Load Input Grid
                Me.Text = DT_CONSTRUCT_VIEW.Rows(0).Item("FORM_TITLE")
                'Die Standards ein/ausblenden
            End If
            Load_TreeViewEbene()
            FormLoaded = True

        Catch ex As System.Exception
            MsgBox("Error while Loading Form" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            System.Windows.Forms.MessageBox.Show(ex.Message)
        End Try
        tslblEntity.Text = ""
        Me.Cursor = Cursors.Default
    End Sub
    Sub Load_TreeViewEbene()
        Try
            Dim sql As String = "SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE PARENT_ID = 0 AND CONSTRUCT_ID = " & CONSTRUCTORID & " ORDER BY SEQUENCE"
            Dim dt As DataTable = ClassDatabase.Return_Datatable(sql)
            Dim GRANDFATHERNODE1 As TreeNode
            Dim GRANDFATHERNODE2 As TreeNode
            Dim FATHERNODE As TreeNode
            If dt Is Nothing Then
                MsgBox("No Result for Level 1-Entities - Check logfile", MsgBoxStyle.Exclamation)
            Else
                If dt.Rows.Count = 1 Then
                    TreeViewEbeneSelect.Nodes.Clear()
                    GRANDFATHERNODE1 = TreeViewEbeneSelect.Nodes.Add(dt.Rows(0).Item("FORM_TITLE").ToString)
                    GRANDFATHERNODE1.Tag = dt.Rows(0).Item("FORM_ID")
                    'Ebene 2 Entities herausfinden
                    sql = "SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND PARENT_ID = " & GRANDFATHERNODE1.Tag & " ORDER BY SEQUENCE"
                    dt = ClassDatabase.Return_Datatable(sql)
                    If dt Is Nothing Then
                        MsgBox("No Result for Level 2-Entities - Check logfile", MsgBoxStyle.Exclamation)
                    Else
                        If dt.Rows.Count = 0 Then
                            tslblStatusMain_show(True, "No Result for Level 2-Entities")
                            ' MsgBox("Not allowed: No Result for Level 2-Entities! Check Config FormConstructor.", MsgBoxStyle.Exclamation)
                        Else
                            For Each rowentity2 As DataRow In dt.Rows
                                FATHERNODE = GRANDFATHERNODE1.Nodes.Add(rowentity2.Item("FORM_TITLE").ToString)
                                FATHERNODE.Tag = rowentity2.Item("FORM_ID")
                                EBENE2_PARENT_ID = dt.Rows(0).Item("PARENT_ID")
                                'Ebene 3 Entities herausfinden
                                Dim DT3 As DataTable
                                sql = "SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND PARENT_ID = " & FATHERNODE.Tag & " ORDER BY SEQUENCE"
                                DT3 = ClassDatabase.Return_Datatable(sql)
                                If DT3 Is Nothing Then
                                    MsgBox("No Result for Level 3-Entities - Check logfile", MsgBoxStyle.Exclamation)
                                Else
                                    For Each rowEntity3 As DataRow In DT3.Rows
                                        Dim CHILDNODE As TreeNode = FATHERNODE.Nodes.Add(rowEntity3.Item("FORM_TITLE").ToString)
                                        CHILDNODE.Tag = rowEntity3.Item("FORM_ID")
                                        EBENE3_PARENT_ID = rowEntity3.Item("PARENT_ID")
                                    Next
                                End If
                            Next
                        End If
                    End If
                ElseIf dt.Rows.Count = 2 Then
                    TreeViewEbeneSelect.Nodes.Clear()
                    GRANDFATHERNODE1 = TreeViewEbeneSelect.Nodes.Add(dt.Rows(0).Item("FORM_TITLE").ToString)
                    GRANDFATHERNODE1.Tag = dt.Rows(0).Item("FORM_ID")
                    GRANDFATHERNODE2 = TreeViewEbeneSelect.Nodes.Add(dt.Rows(1).Item("FORM_TITLE").ToString)
                    GRANDFATHERNODE2.Tag = dt.Rows(1).Item("FORM_ID")
                Else
                    MsgBox("More than 2 results #(" & dt.Rows.Count & ") for Level 1-Entities!", MsgBoxStyle.Exclamation)
                End If
                TreeViewEbeneSelect.ExpandAll()
                TreeViewEbeneSelect.Nodes(0).EnsureVisible()
            End If
        Catch ex As Exception
            MsgBox("Error in Load TreeView Ebene:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub Load_Level1()
        Try
            Dim sql As String = "SELECT * from VWPMO_CONSTRUCTOR_FORMS WHERE PARENT_ID = 0 AND CONSTRUCT_ID = " & CONSTRUCTORID & " ORDER BY SEQUENCE"
            Dim dt As DataTable = ClassDatabase.Return_Datatable(sql)

            If Not IsNothing(dt) Then
                If dt.Rows.Count >= 1 Then
                    Dim tn As TreeNode = TreeViewEbeneSelect.Nodes(0)
                    TreeViewEbeneSelect.SelectedNode = tn
                    TreeViewEbeneSelect.Select()
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in Load_Level1:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
       
    End Sub
    Private Function LoadGrid_Selection(Grid_SQL As String, Datatable_Grid As DataTable)
        Try
            DT_SELECTION = Datatable_Grid
            EBENE_SQLRESULT = Grid_SQL
            Dim i = EBENE_SQLRESULT.ToLower.IndexOf("from")
            EBENE_SQLRESULT = EBENE_SQLRESULT.ToLower.Substring(i)
            ' Alle Checkboxen für aktuelle Ansicht heraussuchen
            Dim sqlcheck As String = "SELECT CONTROL_COLUMN FROM VWPMO_VALUES WHERE CONTROL_TYPE_ID in (10,11) AND FORM_ID = " & CURRENT_FORM_ID
            Dim dtcheck As DataTable = ClassDatabase.Return_Datatable(sqlcheck)
            Dim listcheck As New List(Of String)

            'Liste von allen Spaltentiteln mit Checkbox erstellen
            If dtcheck.Rows.Count > 0 Then
                For Each row As DataRow In dtcheck.Rows
                    listcheck.Add(row.Item(0))
                Next
            End If

            'Duplikate entfernen
            listcheck = listcheck.Distinct().ToList()

            'Grid leeren
            GridControlSelection.DataSource = Nothing
            grvwSelection.Columns.Clear()
            'Databinding Neu
            Me.BindingSourceEntity.DataSource = Datatable_Grid
            GridControlSelection.DataSource = BindingSourceEntity

            ' Den Editor Initialisieren und Optionen setzen
            CheckBoxEditorForDisplay = New RepositoryItemCheckEdit()
            CheckBoxEditorForDisplay.ValueChecked = 1
            CheckBoxEditorForDisplay.ValueUnchecked = 0

            ' Alle Checkbox Spalten durchgehen und CheckBoxEditor zuweisen
            For Each col As String In listcheck
                grvwSelection.GridControl.RepositoryItems.Add(CheckBoxEditorForDisplay)

                If Not IsNothing(grvwSelection.Columns(col)) Then
                    grvwSelection.Columns(col).ColumnEdit = CheckBoxEditorForDisplay
                End If
            Next
            grvwSelection.Columns("Record-ID").OptionsColumn.AllowShowHide = False
            Load_GridSelection_Layout()
            HideColumns()
            Dim selnode As TreeNode = TreeViewEbeneSelect.SelectedNode
            Dim origtext As String = selnode.Text
            If origtext.Contains(" (") Then
                Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)
                selnode.Text = existingstring & " (" & grvwSelection.RowCount & ")"
            Else
                selnode.Text = selnode.Text & " (" & grvwSelection.RowCount & ")"
            End If
        Catch ex As Exception
            MsgBox("Error in LoadGrid_Selection:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Return False
        End Try
        Return True

    End Function
    Sub SelectedRecord_ShowData(GridColumn_String As String, Optional DirectRecID As Integer = 0)
        Try
            Me.pnlDetails.Visible = True
            ZeigeRecordLogsToolStripMenuItem.Enabled = False
            If DirectRecID = 0 Then
                If LogErrorsOnly = False Then ClassLogger.Add(">> Record wird über Datagrid focusedRow geladen", False)
                'Überhaupt Columns in Grid?
                If grvwSelection.Columns.Count = 0 Then
                    Me.pnlDetails.Enabled = False
                    Me.tsbtnshowWorkflowtasks.Enabled = False

                    tsstatus_Detail_show(True, "Keine Columns in Grid")
                    Exit Sub
                End If
                'Überhaupt Rows in Grid?
                If grvwSelection.RowCount > 0 Then
                    Dim Grid_RecordID = grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns(GridColumn_String))
                    If Grid_RecordID Is Nothing = False Then
                        SelectedRecordID = Grid_RecordID
                        CURRENT_RECORD_ID = Grid_RecordID
                    Else
                        tsstatus_Detail_show(True, "Grid_RecordID konnte nicht gewählt werden!")
                        ClassLogger.Add(">> Grid_RecordID konnte nicht gewählt werden - SelectedRecord_ShowData", True)
                        Exit Sub
                    End If
                End If

            Else 'Record wird direkt geladen
                If LogErrorsOnly = False Then ClassLogger.Add(">> Record wird DIREKT geladen", False)
                SelectedRecordID = DirectRecID
                CURRENT_RECORD_ID = DirectRecID
            End If

            Dim Record_Changes As String = "SELECT count(GUID) FROM VWPMO_RECORD_CHANGES WHERE RECORD_ID = " & CURRENT_RECORD_ID
            Dim RC = ClassDatabase.Execute_Scalar(Record_Changes)
            If Not RC Is Nothing Then
                If RC > 0 Then
                    ZeigeRecordLogsToolStripMenuItem.Enabled = True
                End If
            End If
            'Die aktuelle Ebene überprüfen und den Datensatz übergeben, ebenso den PARENT-Record setzen
            Select Case ACT_EBENE
                Case 1
                    CURRENT_PARENTID = 0
                    EBENE1_RECID = SelectedRecordID
                    CURRENT_PARENTID = EBENE1_RECID
                    If Not EBENE1_COLUMNNAME Is Nothing Then
                        EBENE1_GRID_RESULT = Get_GridResult(EBENE1_COLUMNNAME)
                    End If
                Case 2
                    EBENE2_RECID = SelectedRecordID
                    If Not EBENE2_COLUMNNAME Is Nothing Then
                        EBENE2_GRID_RESULT = Get_GridResult(EBENE2_COLUMNNAME)
                        'Dim sql As String = "select @p " & EBENE_SQLRESULT & " where [Record-ID] = " & SelectedRecordID
                        'sql = sql.Replace("@p", EBENE2_COLUMNNAME)
                        'Dim result = ClassDatabase.Execute_Scalar(sql)
                        'EBENE2_GRID_RESULT = result 'grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns(EBENE2_COLUMNNAME))

                    End If
                    If EBENE1_RECID > 0 Then
                        CURRENT_PARENTID = EBENE1_RECID
                    Else
                        CURRENT_PARENTID = EBENE2_RECID
                    End If
                Case 3
                    EBENE3_RECID = SelectedRecordID
                    If Not EBENE3_COLUMNNAME Is Nothing Then
                        EBENE3_GRID_RESULT = Get_GridResult(EBENE3_COLUMNNAME)
                        'EBENE3_GRID_RESULT = grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns(EBENE3_COLUMNNAME))
                    End If
                    If EBENE2_RECID > 0 Then
                        CURRENT_PARENTID = EBENE2_RECID
                    End If
            End Select

            Me.pnlDetails.Enabled = True
            Me.tsbtnshowWorkflowtasks.Enabled = True
            Me.tsbtnshowTaskoverview.Enabled = True
            tsstatus_Detail_show(False, "")
        Catch ex As Exception
            MsgBox("Error in SelectedRecord_ShowData:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Function Get_GridResult(Columnname As String)
        Dim result As String = grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns(Columnname))
        If result = String.Empty Then
            Return "No Column configured"
        Else
            Return result
        End If
    End Function
    Private Function Check_FOLLOWUP_IsConfigured(ENTITY_ID As Integer)
        Try

            Dim sql = "select * from TBPMO_FOLLOW_UP_EMAIL t where t.ACTIVE = 1 and t.DEPENDENT_DATE_CTRL_ID in (select guid from TBPMO_CONTROL where  CONTROL_TYPE_ID = 4 and form_id = " & ENTITY_ID & ")"
            DT_FU_ENTITY = ClassDatabase.Return_Datatable(sql)
            If DT_FU_ENTITY.Rows.Count > 0 Then
                'Die Userauswahl füllen
                Dim DTUser As DataTable = ClassDatabase.Return_Datatable("select guid, username from TBDD_USER t where T.EMAIL IS NOT NULL AND MODULE_RECORD_ORG = 1 order by USERNAME")
                cmbWHUser.DataSource = DTUser
                cmbWHUser.DisplayMember = DTUser.Columns(1).ColumnName
                cmbWHUser.ValueMember = DTUser.Columns(0).ColumnName
                TabPageFollowUp.PageVisible = True
                FOLLOW_UPisActive = True

                'Die Wiedervorlageprofile in den Listview laden
                ListViewFollowUp.Items.Clear()
                Dim anz As Integer = 0
                For Each DR As DataRow In DT_FU_ENTITY.Rows
                    ListViewFollowUp.Items.Add(DR.Item("GUID"))
                    ListViewFollowUp.Items(anz).SubItems.Add(DR.Item("NAME"))
                    anz += 1
                Next

            Else
                FOLLOW_UPisActive = False
                TabPageFollowUp.PageVisible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Check Follow Up:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            windream_Docshow = False
        End Try
    End Function
    Private Function Check_windream_Show(FORM_VIEW_ID As Integer)
        Try
            Dim sql = "SELECT * FROM TBPMO_FORM_VIEW WHERE WINDREAM_SEARCH <> '' AND GUID = " & FORM_VIEW_ID
            Dim DTWD As DataTable = ClassDatabase.Return_Datatable(sql)
            If DTWD.Rows.Count = 1 Then
                TabPageWD_Files.PageVisible = True

                If IsDBNull(DTWD.Rows(0).Item(0)) Then
                    windream_Docshow = False
                    WindreamSucheNeuLadenToolStripMenuItem.Visible = False
                    Exit Function
                End If
                WindreamSucheNeuLadenToolStripMenuItem.Visible = True
                windream_Docshow = True
            Else
                windream_Docshow = False
                TabPageWD_Files.PageVisible = False

                WindreamSucheNeuLadenToolStripMenuItem.Visible = False
            End If
        Catch ex As Exception
            MsgBox("Error in Check windream show:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            windream_Docshow = False
        End Try

    End Function

    Private Sub Load_Value(recID As Integer, CONTROLID As Integer, control As Control)
        Try
            Dim SQL = "SELECT * FROM VWPMO_VALUES WHERE RECORD_ID = " & recID & " and CONTROL_ID = " & CONTROLID
            Dim DT As DataTable = ClassDatabase.Return_Datatable(SQL)
            Dim result = DT.Rows(0).Item("VALUE")

            'Dim RecordExists = ClassDatabase.Execute_Scalar(String.Format("SELECT GUID FROM VWPMO_VALUES WHERE RECORD_ID = {0} AND CONTROL_ID = {1}", recID, CONTROLID))

            ClassControlValues.ClearControlValue(control)

            Select Case DT.Rows(0).Item("CONTROL_TYPE_ID")
                Case 2 ' TextBox
                    Dim textbox As TextBox = DirectCast(control, TextBox)
                    textbox.Text = result
                Case 10 ' CheckBox
                    Dim checkbox As CheckBox = DirectCast(control, CheckBox)
                    checkbox.Checked = CBool(result)
                Case 11 'RadioButton
                    Dim radio As RadioButton = DirectCast(control, RadioButton)
                    radio.Checked = CBool(result)
                Case 3 ' ComboBox
                    Dim combobox As ComboBox = DirectCast(control, ComboBox)
                    combobox.SelectedIndex = combobox.FindStringExact(result)
                Case 4 'DateTimePicker
                    'Console.WriteLine(result)
                    If result = "" Then
                        result = Now
                    End If
                    Dim datepicker As DevExpress.XtraEditors.DateEdit = DirectCast(control, DevExpress.XtraEditors.DateEdit)
                    datepicker.DateTime = Date.Parse(result)
                Case Else
                    'MsgBox(DT.Rows(0).Item("CONTROL_TYPE_ID"))
            End Select
        Catch ex As Exception
            MsgBox("Error in Load_Value:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Sub OpenFormData(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Try
            Dim Control As Control = sender
            Dim ControlName As String = Control.Name
            Dim ControlId As Integer = GetControlID_for_Name(ControlName, CURRENT_FORM_ID)

            Dim dr As DataRow = ClassFunctionCommands.LoadFunction(ControlId)

            If IsDBNull(dr.Item("INTEGER1")) OrElse dr.Item("INTEGER1") = 0 Then
                MsgBox("FormId ist nicht definiert für " & ControlName)
                Exit Sub
            End If

            If IsDBNull(dr.Item("INTEGER2")) OrElse dr.Item("INTEGER2") = 0 Then
                MsgBox("ScreenId ist nicht definiert für " & ControlName)
                Exit Sub
            End If

            Dim FormId As Integer = dr.Item("INTEGER1")
            Dim ScreenId As Integer = dr.Item("INTEGER2")

            Cursor = Cursors.WaitCursor
            OpenFormInputFor(FormId, ScreenId)

            Cursor = Cursors.Default
        Catch ex As Exception
            MsgBox("Error in OpenFormData:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Sub NewEditAppointment(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
        Try
            Dim ctrl As Control = sender
            ClassFunctionCommandsUI.NewEditAppointment(ctrl.Name, CURRENT_FORM_ID, CURRENT_RECORD_ID, pnlDetails.Controls)
        Catch ex As Exception
            MsgBox("Error in OpenEditAppointment:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
   
    Sub EditAppointment(ByVal sender As Control, FormID As Integer)
        Try
            ' Load All appointments first
            frmCalendar.TBPMO_RESOURCESTableAdapter.Fill(frmCalendar.DD_DMSDataSetCalendar.TBPMO_RESOURCES)
            frmCalendar.TBPMO_APPOINTMENTSTableAdapter.Fill(frmCalendar.DD_DMSDataSetCalendar.TBPMO_APPOINTMENTS)

            Dim apt As Appointment = frmCalendar.SchedulerStorage1.Appointments.Items.Find(AddressOf FindAppointment)
            If apt IsNot Nothing Then
                frmCalendar.SchedulerControl1.ShowEditAppointmentForm(apt)
            End If

        Catch ex As Exception
            MsgBox("Error in EditAppointment:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Function FindAppointment(ByVal apt As Appointment) As Boolean
        Return Convert.ToInt32(apt.CustomFields("RecordID")) = SelectedRecordID
    End Function

    Private Sub OnRecordChanged(sender As Object, e As System.EventArgs)
        RECORD_CHANGED = True
    End Sub

    Sub Load_Controls(FORM_VIEW_ID As Integer)
        thisFORMVIEW_ID = FORM_VIEW_ID
        CURRENT_FORM_ID = ClassDatabase.Execute_Scalar("SELECT FORM_ID FROM TBPMO_FORM_VIEW WHERE GUID = " & FORM_VIEW_ID)
        CtrlBuilder = New ClassControlBuilder(pnlDetails, ttToolTip)
        'LoadControls(thisFormId)
        CtrlCommandUI = New ClassControlCommandsUI(CtrlBuilder,
                                                   contextMenuCombo,
                                                   AddressOf NewEditAppointment,
                                                   AddressOf OpenFormData)
        CtrlCommandUI.LoadControls(CURRENT_FORM_ID)
        AddHandler CtrlBuilder.OnRecordChanged, AddressOf OnRecordChanged

    End Sub
    Sub set_pnlsize()
        Try
            Dim Height = ClassDatabase.Execute_Scalar("SELECT HEIGHT FROM TBPMO_FORM_VIEW WHERE FORM_ID = " & CURRENT_FORM_ID & " and SCREEN_ID = " & CURRENT_SCREEN_ID)
            Dim width = ClassDatabase.Execute_Scalar("SELECT WIDTH FROM TBPMO_FORM_VIEW WHERE FORM_ID = " & CURRENT_FORM_ID & " and SCREEN_ID = " & CURRENT_SCREEN_ID)

            If Not IsDBNull(Height) Then
                'SplitContainerControlDetails.SplitterPosition = Height + 50
                'Me.pnlDetails.Height = Height
                'If Not IsDBNull(width) Then
                '    Me.pnlDetails.Width = width
                'End If
            End If
        Catch ex As Exception
            MsgBox("Error in set_pnlsize:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Function GetControlID(recID As Integer, control As Control) As Integer
        Try
            Dim ID As Integer = ClassDatabase.Execute_Scalar("SELECT CONTROL_ID FROM VWPMO_VALUES WHERE RECORD_ID = " & recID & " and CONTROL_NAME = '" & control.Name & "'")
            If ID > 0 Then
                Return ID
            Else
                Return -1
            End If
        Catch ex As Exception
            MsgBox("Error in GetControlID:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Function
    Public Sub tsstatus_Detail_show(vis As Boolean, txt As String, Optional state As String = "NONE")
        Me.tsstatus_Detail.Text = txt
        tsstatus_Detail.Visible = vis
        Select Case state
            Case "insert"
                tsstatus_Detail.BackColor = Color.Yellow
            Case "update"
                tsstatus_Detail.BackColor = Color.LightBlue
            Case Else
                tsstatus_Detail.BackColor = Color.LightGray
        End Select
    End Sub
    Public Sub tslblStatusMain_show(vis As Boolean, txt As String)
        Me.tslblStatusMain.Text = txt
        tslblStatusMain.Visible = vis
    End Sub

    Public Sub Refresh_CreatedChangedRecordByID(RECORD_ID As Integer)
        Try
            Dim result = ClassDatabase.Execute_Scalar("select 'Added by ' + ADDED_WHO + ' when ' + CONVERT(VARCHAR(16),ADDED_WHEN,20) + ', Changed by ' + COALESCE(CHANGED_WHO,'') + ' when ' + COALESCE(CONVERT(VARCHAR(16),CHANGED_WHEN,20),'') FROM TBPMO_RECORD WHERE GUID = " & RECORD_ID)
            If IsDBNull(result) Or IsNothing(result) Then
                Me.tserstellt_Details.Text = ""
            Else
                Select Case CURRENT_FORM_TYPE
                    Case 5
                        Me.tserstellt_Details.Text = "Group-Record (" & RECORD_ID & ") - " & result.ToString
                    Case Else
                        Me.tserstellt_Details.Text = "Record (" & RECORD_ID & ") - " & result.ToString
                End Select

            End If
            tserstellt_Details.Visible = True
        Catch ex As System.Exception
            MsgBox("Error in Refresh_CreatedChangedRecordByID:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub RUN_WD_SEARCH(BaseSearch As String, Type As String)
        Try
            If Not windream_Docshow = True Or Sett_LoadWD_Docs = False Or TCDetails.SelectedTabPageIndex <> 1 Then
                Exit Sub
            End If
            Cursor = Cursors.WaitCursor
            Dim DTWD As DataTable
            If Type = "ENTITY" Then
                Dim _sql = "SELECT WINDREAM_SEARCH,SEARCH_PATTERN1,SEARCH_PATTERN2,SEARCH_PATTERN3,SEARCH_PATTERN4,SEARCH_PATTERN5 FROM TBPMO_FORM_CONSTRUCTOR_DETAIL WHERE WINDREAM_SEARCH <> '' AND FORM_ID = " & CURRENT_FORM_ID
                DTWD = ClassDatabase.Return_Datatable(_sql)
                If DTWD.Rows.Count = 1 Then
                    If IsDBNull(DTWD.Rows(0).Item(0)) Then
                        Clear_Windream_ResultList()
                        Exit Sub
                    End If
                    tslblWindreamView.Text = "Windream-Dokumente für Entität: " & ACT_EBENE_STRING
                Else
                    Clear_Windream_ResultList()
                    Exit Sub
                End If
            Else
                Dim sql = "SELECT WINDREAM_SEARCH,SEARCH_PATTERN1,SEARCH_PATTERN2,SEARCH_PATTERN3,SEARCH_PATTERN4,SEARCH_PATTERN5 FROM TBPMO_FORM_VIEW WHERE WINDREAM_SEARCH <> '' AND FORM_ID = " & CURRENT_FORM_ID
                DTWD = ClassDatabase.Return_Datatable(sql)
                If DTWD.Rows.Count = 1 Then
                    If IsDBNull(DTWD.Rows(0).Item(0)) Then
                        Clear_Windream_ResultList()
                        Exit Sub
                    End If
                    tslblWindreamView.Text = "Windream-Dokumente für Record: " & SelectedRecordID
                Else
                    Clear_Windream_ResultList()
                    Exit Sub
                End If
            End If
            'Die SearchPatterns durchlaufen und zwischenspeichern
            If IsDBNull(DTWD.Rows(0).Item(0)) Then
                Clear_Windream_ResultList()
                Exit Sub
            End If
            BaseSearch = DTWD.Rows(0).Item(0)
            SP1 = DTWD.Rows(0).Item(1)
            If IsDBNull(DTWD.Rows(0).Item(2)) Then
                SP2 = ""
            Else
                SP2 = DTWD.Rows(0).Item(2)
            End If
            If IsDBNull(DTWD.Rows(0).Item(3)) Then
                SP3 = ""
            Else
                SP3 = DTWD.Rows(0).Item(3)
            End If
            If IsDBNull(DTWD.Rows(0).Item(4)) Then
                SP4 = ""
            Else
                SP4 = DTWD.Rows(0).Item(4)
            End If
            If IsDBNull(DTWD.Rows(0).Item(5)) Then
                SP5 = ""
            Else
                SP5 = DTWD.Rows(0).Item(5)
            End If

            'Eine tempfile generieren
            Dim tempFilename1 = My.Computer.FileSystem.GetTempFileName()
            'Nur den Filenamen ohne Erweiterung
            Dim tempName = Path.GetFileNameWithoutExtension(tempFilename1)
            'tempfile lsöchen
            If My.Computer.FileSystem.FileExists(tempFilename1) Then
                My.Computer.FileSystem.DeleteFile(tempFilename1)
            End If
            Try
                Dim temppath = Path.GetTempPath

                Dim EncodingFormat As Encoding
                Dim WDUnicode = ClassDatabase.Execute_Scalar("SELECT WD_UNICODE FROM TBPMO_KONFIGURATION WHERE GUID = 1")
                If WDUnicode = True Then
                    EncodingFormat = Encoding.GetEncoding(1252) '1252
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Unicode is used (Encoding.GetEncoding(1252))", False)
                Else
                    If LogErrorsOnly = False Then ClassLogger.Add(">> UTF8 (Encoding.GetEncoding(65001))", False)
                    EncodingFormat = Encoding.GetEncoding(65001)
                End If


                Dim fileContents As String
                If LogErrorsOnly = False Then ClassLogger.Add(">> ReadAlltext: " & windream_temp_search, False)
                fileContents = My.Computer.FileSystem.ReadAllText(BaseSearch, EncodingFormat) ', System.Text.Encoding.Unicode
                If LogErrorsOnly = False Then ClassLogger.Add(">> fileContents geladen", False)
                fileContents = fileContents.Replace("Í", "Ö")
                Dim _sp1 = SP1
                Dim _sp2 = SP2
                Dim _sp3 = SP3
                Dim _sp4 = SP4
                Dim _sp5 = SP5



                If _sp1.ToString <> String.Empty Then
                    _sp1 = Return_SearchPattern(_sp1.ToString)
                    fileContents = fileContents.Replace("%pattern1%", _sp1)
                    fileContents = fileContents.Replace("471101", _sp1)
                End If
                If _sp2.ToString <> String.Empty Then
                    _sp2 = Return_SearchPattern(_sp2.ToString)
                    If _sp2 = 0 Then
                        _sp2 = ""
                    End If
                    fileContents = fileContents.Replace("%pattern2%", _sp2)
                    fileContents = fileContents.Replace("471102", _sp2)
                End If
                If _sp3.ToString <> String.Empty Then
                    _sp3 = Return_SearchPattern(_sp3.ToString)
                    If _sp3 = 0 Then
                        _sp3 = ""
                    End If
                    fileContents = fileContents.Replace("%pattern3%", _sp3)
                    fileContents = fileContents.Replace("471103", _sp3)
                End If
                If _sp4.ToString <> String.Empty Then
                    _sp4 = Return_SearchPattern(_sp4.ToString)
                    If _sp4 = 0 Then
                        _sp4 = ""
                    End If
                    fileContents = fileContents.Replace("%pattern4%", _sp4)
                    fileContents = fileContents.Replace("471104", _sp4)
                End If
                If _sp5.ToString <> String.Empty Then
                    _sp5 = Return_SearchPattern(_sp5.ToString)
                    If _sp5 = 0 Then
                        _sp5 = ""
                    End If
                    fileContents = fileContents.Replace("%pattern5%", _sp5)
                    fileContents = fileContents.Replace("471105", _sp5)
                End If
                'Die windream File zusammensetzen
                windream_temp_search = temppath & tempName & ".wdf"
                TEMP_FILES.Add(windream_temp_search)
                'Die File schreiben
                My.Computer.FileSystem.WriteAllText(windream_temp_search, fileContents, False, EncodingFormat)
                My.Computer.FileSystem.WriteAllText(temppath & "SEARCH_COPY.wdf", fileContents, False, EncodingFormat)
                ' XML-Datei öffnen und laden
                Dim Stream As New IO.StreamReader(CStr(windream_temp_search), EncodingFormat)
                Dim Reader As New System.Xml.XmlTextReader(Stream)

                ' XML-Datei initialisieren
                Dim xml As New System.Xml.XmlDocument()
                ' XML-Datei öffnen und laden
                xml.Load(Reader)
                Reader.Close()
                xml.Save(windream_temp_search)
                If LogErrorsOnly = False Then ClassLogger.Add(">> Xml Generiert: " & windream_temp_search, False)

                Dim windreamSucheErgebnisse As WMObjects
                Try
                    windreamSucheErgebnisse = Me._windream.GetSearchDocuments(windream_temp_search)
                Catch ex As Exception
                    MsgBox("Error in windreamSucheErgebnisse:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                End Try

                If windreamSucheErgebnisse.Count > 0 Then
                    TabPageWD_Files.Text = "windream-Dateien (" & windreamSucheErgebnisse.Count & ")"

                    AxObjectListControl.SetIconMode(True)
                    AxObjectListControl.RemoveAllColumnHeader()
                    Dim param As New List(Of String)
                    'The file name
                    param.Add("szLongName")
                    'The document-Type
                    param.Add("szText37")
                    'Versionsnummer
                    param.Add("dwVersionNumber")
                    'Datumsangaben
                    param.Add("dwCreationDate")
                    param.Add("dwCreation_Time")
                    Me.AxObjectListControl.SetSession(ClassWindream.oSession, "", "")
                    'Change the satus icon
                    'ICON STATES:
                    Me.AxObjectListControl.SetStatusIcon(0)

                    'Change the icon
                    Me.AxObjectListControl.SetStatusIcon(2)
                    'Add all search params
                    For Each spar As String In param
                        Dim width As Integer = 200
                        Select Case spar
                            Case "szLongName"
                                'Dateiname
                                width = 300
                            Case "szText37"
                                'Dokumentart
                                width = 160
                            Case "dwCreationDate"
                                'Erstelldatum
                                width = 90
                            Case "dwCreation_Time"
                                'Erstell-Zeit
                                width = 120
                        End Select
                        'You need to use the column name here
                        'Please note that some attributes or indices will not be displayed
                        'Try not to add the same header twice, it will throw cause problems if you do that
                        Me.AxObjectListControl.AddColumnHeader(spar, width)
                    Next
                    If LogErrorsOnly = False Then ClassLogger.Add(">> AxObjectListControl geladen ", False)
                    'Execute the search
                    Dim results As WMObjects = windreamSucheErgebnisse
                    If LogErrorsOnly = False Then ClassLogger.Add(">> results geladen ", False)
                    'Set the contents without displaying them
                    AxObjectListControl.SetContentsEx(results)
                    'Change the icon
                    AxObjectListControl.SetStatusIcon(5)
                    'Display the results...
                    'The Previous Object Count
                    Dim poc As Integer = 0
                    'Display new objects, as long as the objectcount changes after displaying the objects

                    Do Until (poc <> AxObjectListControl.GetObjectCount)
                        poc = AxObjectListControl.GetObjectCount
                        'If you want, you can display more items at a timeRefresh_FollowUp_TabHeader
                        'But do not display to many at a time or the user interface could freeze
                        'Maybe try 50
                        AxObjectListControl.DisplayResults(WDResultListCount)
                    Loop
                    AxObjectListControl.SetStatusIcon(3)
                Else
                    Clear_Windream_ResultList()
                End If

            Catch ex As Exception
                MsgBox("Error in execute-windreamSearch:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try

            Cursor = Cursors.Default
        Catch ex As Exception
            MsgBox("Error in RUN_WD_SEARCH:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Cursor = Cursors.Default
        End Try


    End Sub
    Private Sub Refresh_FollowUp_TabHeader()
        Try
            DT_FU_Record = ClassDatabase.Return_Datatable("select * from VWPMO_FOLLOW_UP_EMAIL_ENTITY_RECORD where Record_ID = " & CURRENT_RECORD_ID, "Refresh FollowUp TabHeader")
            If IsNothing(DT_FU_Record) Then
                TabPageFollowUp.Text = "Wiedervorlage (Nicht Abrufbar)"
                Exit Sub
            End If
            If DT_FU_Record.Rows.Count = 0 Then
                TabPageFollowUp.Text = "Wiedervorlage (Nicht aktiviert)"
            Else
                TabPageFollowUp.Text = "Wiedervorlage (Aktive Profile)"
            End If
        Catch ex As Exception
            MsgBox("Error in Refresh_FollowUp_TabHeader:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Private Sub Refresh_FollowUps()
        Try
            If DT_FU_ENTITY.Rows.Count > 0 Then
                grpbxFU_Profile.Enabled = False
            End If
        Catch ex As Exception
            MsgBox("Error in Refresh_FollowUps:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Sub Clear_Windream_ResultList()
        AxObjectListControl.RemoveAllColumnHeader()
        Me.AxObjectListControl.ClearResultList()
        TabPageWD_Files.Text = "windream-Dateien"
    End Sub
    Private Function Return_SearchPattern(ByVal content As String)
        Select Case content.ToUpper
            Case "@Record-ID".ToUpper
                Return CURRENT_RECORD_ID
            Case "@EntityID".ToUpper
                Return CURRENT_FORM_ID
            Case "@ParentID".ToUpper
                Return CURRENT_PARENTID
            Case Else
                MsgBox("Undefinierter Pattern '" & content & "' in der Windream-SuchKonfiguration. Bitte den Administrator verständigen", MsgBoxStyle.Exclamation)
                ClassLogger.Add(" >> Undefinierter Such-Pattern: " & content, True)
        End Select
    End Function

    Private Sub tsbtnAddForm2_Click(sender As Object, e As EventArgs) Handles tsbtnRecordAdd.Click
        If CtrlCommandUI.IsInsert = True Then
            Exit Sub
        End If
        RECORD_CHANGED = True
        'Das Flag INSERT setzen
        Me.pnlDetails.Enabled = True
        Me.tsbtnshowWorkflowtasks.Enabled = True
        ClassControlValues.LoadDefaultValues(CURRENT_FORM_ID, SelectedRecordID, pnlDetails.Controls)
        CtrlCommandUI.IsInsert = True

    End Sub

    Private Function Update_Record_OnChange() As String
        ' Record Speichern
        Dim ResultMessage = CtrlCommandUI.SaveRecord(SelectedRecordID, CURRENT_FORM_ID, CURRENT_PARENTID)
        'Jetzt die für die Entität notwendigen Prroceduren ausführen
        Customer_Run_Procedures()

        Return ResultMessage
    End Function

    Private Sub Customer_Run_Procedures()
        Try
            Dim DT As DataTable = ClassDatabase.Return_Datatable("SELECT * FROM TBPMO_RUN_PROCEDURES WHERE FORM_ID = " & CURRENT_FORM_ID)
            If Not DT Is Nothing Then
                For Each row As DataRow In DT.Rows
                    Dim prsql As String = row.Item("EXECUTE_COMMAND")
                    prsql = prsql.ToUpper.Replace("@FORM_ID", CURRENT_FORM_ID)
                    prsql = prsql.ToUpper.Replace("@RECORD_ID", CURRENT_RECORD_ID)
                    ClassDatabase.Execute_non_Query(prsql, True)
                Next
            End If
        Catch ex As Exception
            MsgBox("Error in Customer_Run_Procedures:" & vbNewLine & ex.Message)
        End Try
    End Sub

    Private Sub tsbtnSaveForm2_Click(sender As Object, e As EventArgs) Handles tsbtnRecordSave.Click
        Try
            tserstellt_Details.Visible = False
            SaveRoutine_Active = True
            If CtrlCommandUI.IsInsert = True Then
                EDIT_STATE = "insert"
            Else
                EDIT_STATE = "update"
                NEW_RECORD_ID = 0
                If RECORD_CHANGED = False Then
                    tslblStatusMain_show(True, "KEINE Änderungen an Datensatz.")
                    Exit Sub
                End If
            End If

            Dim ResultMessage = Update_Record_OnChange()
            tsstatus_Detail_show(True, ResultMessage, EDIT_STATE)

            Dim recid As Integer
            If EDIT_STATE = "update" Then
                recid = CURRENT_RECORD_ID
            Else
                recid = NEW_RECORD_ID
            End If
            SelectedRecordID = recid
            CURRENT_RECORD_ID = recid

            'Load_Data_for_TreeView()
            'dd()
            'Search_RowHandle(recid)
            If EDIT_STATE = "insert" Then
                'Weil es ein Insert war müssen noch die Daten gespeichert/erneuert werden
                Select Case ACT_EBENE
                    Case 1
                        EBENE1_RECID = recid
                        For Each row As DataRow In DT_SELECTION.Rows
                            If row.Item("Record-ID") = SelectedRecordID Then
                                EBENE1_GRID_RESULT = row.Item(EBENE1_COLUMNNAME)
                            End If
                        Next
                    Case 2
                        EBENE2_RECID = recid
                        For Each row As DataRow In DT_SELECTION.Rows
                            If row.Item("Record-ID") = SelectedRecordID Then
                                EBENE2_GRID_RESULT = row.Item(EBENE2_COLUMNNAME)
                            End If
                        Next
                        If EBENE1_RECID = 0 Then
                            'Bis jetzt konnte noch keine Parent-ID angelegt werden!
                            MsgBox("Achtung es wurde noch keine Parent-Verknüpfung angelegt!", MsgBoxStyle.Exclamation)
                            Show_Verknuepfungen()
                        End If
                End Select
            ElseIf EDIT_STATE = "update" Then
                'Weil es ein Insert war müssen noch die Daten gespeichert/erneuert werden
                Select Case ACT_EBENE
                    Case 1
                        EBENE1_RECID = recid
                        For Each row As DataRow In DT_SELECTION.Rows
                            If row.Item("Record-ID") = SelectedRecordID Then
                                EBENE1_GRID_RESULT = row.Item(EBENE1_COLUMNNAME)
                            End If
                        Next
                    Case 2
                        EBENE2_RECID = recid
                        For Each row As DataRow In DT_SELECTION.Rows
                            If row.Item("Record-ID") = SelectedRecordID Then
                                EBENE2_GRID_RESULT = row.Item(EBENE2_COLUMNNAME)
                            End If
                        Next
                End Select
            End If
            'ddd()
            'Jetzt den Record nochmal laden
            SelectedRecord_ShowData("Record-ID", SelectedRecordID)
            tslblStatusMain_show(True, "Record gespeichert - " & Now)
            Refresh_CreatedChangedRecordByID(SelectedRecordID)
            '  TabPageDetails.Text = "Detaileingabe zu '" & ACT_EBENE_STRING & "' - Record(" & SelectedRecordID & ")"
            'Die Values in die Controls laden
            ' Load_Control_Values(CtrlBuilder.AllControls)
            'Refresh_Treeview_SelectedData()
            Anzeige_Selected_Entity()
            'Die Daten neu laden
            'Load_Data_for_TreeView()
            'Und dann den Focus wieder setzen
            If EDIT_STATE = "insert" Then
                'Die Daten neu laden
                Load_Entity_Data_Only()
                Search_RowHandle(NEW_RECORD_ID)
            Else
                'Die Daten neu laden
                Load_Entity_Data_Only()
                Search_RowHandle(CURRENT_RECORD_ID)
                'Die Daten auf dem Panel laden
                ClassControlValues.LoadControlValuesNeu(CURRENT_RECORD_ID, CURRENT_PARENTID,CURRENT_FORM_ID, CtrlBuilder.AllControls)
                ClassControlValues.LoadControlValuesList(CURRENT_RECORD_ID, CURRENT_PARENTID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
                pnlDetails.Enabled = True
            End If
        Catch ex As Exception
            MsgBox("Error in Save Data:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
        EDIT_STATE = "none"
        RECORD_CHANGED = False
        SaveRoutine_Active = False
    End Sub
    Sub Search_RowHandle(Value As String)
        Try
            Dim rowHandle As Integer = DT_SELECTION.Rows.IndexOf(DT_SELECTION.Rows.Find(Value))
            If rowHandle > 0 Then
                grvwSelection.FocusedRowHandle = rowHandle
            End If
        Catch ex As Exception
            ClassLogger.Add("Error in Search_RowHandle: " & ex.Message, False)
        End Try
    End Sub

    Sub Check_Dropped_Files(FORMVIEW_ID As Integer)
        Try
            CURRENT_FORMVIEW_ID = FORMVIEW_ID
            For Each Str As Object In ClassDragDrop.files_dropped
                If Not IsNothing(Str) Then
                    ClassLogger.Add(">> Check_Dropped_Files:" & Str.ToString, False)
                    Dim DropType = Str.Substring(0, Str.LastIndexOf("@") + 1)
                    Dim CURRENT_WORKFILE = Str.Substring(Str.LastIndexOf("@") + 1)
                    TBPMO_FILES_USERTableAdapter.cmdInsert(CURRENT_WORKFILE, Environment.UserName, DropType)
                End If
              
            Next
            TBPMO_FILES_USERTableAdapter.Fill(DD_DMSDataSet.TBPMO_FILES_USER, Environment.UserName)
            For Each Filerow As DataRow In DD_DMSDataSet.TBPMO_FILES_USER.Rows
                Dim worked = ClassDatabase.Execute_Scalar("SELECT WORKED FROM TBPMO_FILES_USER WHERE GUID = " & Filerow.Item("GUID"))
                If worked = False Then
                    'Dim datei = Str.ToString.Replace("@DROPFROMFSYSTEM@", "")
                    CURRENT_FILEID = Filerow.Item(0)
                    frmWD_Index_Dokart.ShowDialog()
                    RUN_WD_SEARCH(WD_Suche, "RECORD")
                End If


            Next
        Catch ex As Exception
            MsgBox("Check_Dropped_Files: " & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub tsbtndeleteForm2_Click(sender As Object, e As EventArgs) Handles tsbtnRecorddelete.Click
        Dim result As MsgBoxResult
        result = MessageBox.Show("Möchten Sie den Datensatz wirklich löschen?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
        If result = MsgBoxResult.Yes Then
            EDIT_STATE = "delete"
            If CtrlCommandUI.DeleteRecord(SelectedRecordID) = True Then
                tsstatus_Detail_show(True, "Der Datensatz " & SelectedRecordID & " wurde erfolgreich gelöscht - " & Now)
                Refresh_CreatedChangedRecordByID(SelectedRecordID)
                Load_Data_for_TreeView()
            End If
        End If
        EDIT_STATE = "none"


    End Sub
    Sub Show_act_WFTask()
        Try
            Me.VWPMO_WF_ACTIVETableAdapter.FillByRecord(Me.DD_DMSDataSet.VWPMO_WF_ACTIVE, CURRENT_RECORD_ID, Environment.UserName)
            tslblactWFState.BackColor = Color.Black
            If DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows.Count > 0 Then
                CURRENT_TASK_ID = Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("WF_TASK_ID")
                Dim text = "Task: " & Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("TITLE")
                text += " - " & Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("STATE_DESC")
                text += " - " & Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("DUE_DATE")
                tslblactWFState.Text = text
                tslblactWFState.Visible = True
                tsbtnshowWorkflowtasks.Visible = True
                tsbtnshowWorkflowtasks.Enabled = True

                Dim Colorstring = Me.DD_DMSDataSet.VWPMO_WF_ACTIVE.Rows(0).Item("COLOR")
                If IsDBNull(Colorstring) Then
                    Exit Sub
                End If
                If Colorstring <> "" Then
                    grvwSelection.Appearance.FocusedRow.BackColor = ColorTranslator.FromWin32(CInt(Colorstring))
                    'grvwSelection.Appearance.FocusedRow.ForeColor = Color.Yellow
                    tslblactWFState.BackColor = ColorTranslator.FromWin32(CInt(Colorstring))
                    Select Case tslblactWFState.BackColor
                        Case Color.Red
                            tslblactWFState.ForeColor = Color.White
                    End Select
                End If

            Else
                tslblactWFState.Visible = False
                tsbtnshowWorkflowtasks.Visible = False
                grvwSelection.Appearance.FocusedRow.BackColor = Color.Fuchsia
            End If
            Dim sql1 As String = "SELECT COUNT(*) FROM TBPMO_WORKFLOW_FORM where FORM_ID = @FORM_ID"
            sql1 = sql1.Replace("@FORM_ID", CURRENT_FORM_ID)
            Dim result As Integer = ClassDatabase.Execute_Scalar(sql1)
            If result > 0 Then
                tsbtnshowWorkflowtasks.Visible = True
                tsbtnshowWorkflowtasks.Enabled = True
            End If


        Catch ex As Exception
            MsgBox("Error in Show act WFTask: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub tsbtnshowWorkflowtasks_Click(sender As Object, e As EventArgs) Handles tsbtnshowWorkflowtasks.Click
        If SelectedRecordID > 0 Then
            frmWF_TaskEditor.ShowDialog()
            Show_act_WFTask()
            Refresh_TaskOverview()
        End If
    End Sub


    Private Sub ToolStripButton5_Click(sender As Object, e As EventArgs) Handles tsbtnOverviewRefresh.Click
        Check_Record_Changed()
        Load_Data_for_TreeView()
    End Sub

    Sub Refresh_TaskOverview()
        Dim frmCollection As New FormCollection()
        frmCollection = Application.OpenForms()
        If frmTaskOverview.IsHandleCreated Then
            If Sett_TaskOverviewKeepInFront = True Then
                frmTaskOverview.Refresh()
            End If
            'Else
            '    Console.WriteLine("frmTaskOverview NICHT geladen")
        End If
    End Sub
    'Private Sub GridView2_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridView2.FocusedRowChanged
    '    If loaded = True Then
    '        thisFORMVIEW_ID = DT_CONSTRUCT_VIEW.Rows(0).Item("FORM2_FVID")
    '        Dim SQL As String = "SELECT FORM_ID FROM TBPMO_FORM_VIEW WHERE GUID = " & DT_CONSTRUCT_VIEW.Rows(0).Item("FORM2_FVID")
    '        thisFormId = ClassDatabase.Execute_Scalar(SQL)
    '        Load_DataforRecord(GridView2, act_ParentEntity_String)
    '        Refresh_TaskOverview()
    '        GridView2.Appearance.FocusedRow.BackColor = Color.OrangeRed
    '    End If
    'End Sub

    Private Sub ToolStripButton7_Click(sender As Object, e As EventArgs) Handles tsbtnshowTaskoverview.Click
        Dim Record_ID = grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns("Record-ID").FieldName)

        'Dim RowView As DataRowView = BindingSourceForm2.Item(BindingSourceForm2.Position)
        If Record_ID Is Nothing = False Then
            If (Not IsDBNull(Record_ID)) Then
                SelectedRecordID = Record_ID
                CURRENT_RECORD_ID = SelectedRecordID
                frmTaskOverview.Show()
            End If
        End If
    End Sub

    Private Sub StammdatenEditierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles StammdatenEditierenToolStripMenuItem.Click
        Dim MenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim ContextMenu As ContextMenuStrip = MenuItem.Owner
        Dim SourceControl As Control = ContextMenu.SourceControl
        Dim MasterDataId As Integer = SourceControl.Tag

        CURRENT_MASTER_FORM_ID = MasterDataId
        ' frmQuickEdit.Show()
        frmQuickInput.ShowDialog()
    End Sub
    Private Sub AxObjectListControl_ItemDblClick(sender As Object, e As AxOBJECTLISTCONTROLLib._DObjectListControlEvents_ItemDblClickEvent) Handles AxObjectListControl.ItemDblClick
        Dim _index = AxObjectListControl.GetFirstSelectedObject
        Dim path As String = AxObjectListControl.GetObjectPath(_index)
        path = path.Replace("?", vWLaufwerk)
        If System.IO.File.Exists(path) Then
            Try
                Dim p As New Process()
                p.StartInfo.FileName = path
                'p.StartInfo.WindowStyle = ProcessWindowStyle.Normal
                p.Start()
                p.WaitForExit()
                p.Close()
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical, "Fehler bei Öffnen einer windream-Datei:")
            End Try
        End If

    End Sub
    Sub Load_GridSelection_Layout()
        Try
            Dim XMLPath = GetSelectionGridName()
            If File.Exists(XMLPath) Then
                GridControlSelection.MainView.RestoreLayoutFromXml(XMLPath)
                grvwSelection.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                grvwSelection.ClearSelection()
                grvwSelection.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try
    End Sub
    Sub Load_GridViewParentEntity_Layout()
        Try
            Dim XMLPath = System.IO.Path.Combine(Application.UserAppDataPath(), GridControlParentEntity.Name & "-CONSTRUCT-" & CONSTRUCTORID & "-UserLayout.xml")
            If File.Exists(XMLPath) Then
                GridControlParentEntity.MainView.RestoreLayoutFromXml(XMLPath)
                GridViewParentEntity.ClearColumnsFilter()
                'grvwSelection.ClearGrouping()
                GridViewParentEntity.ClearSelection()
                GridViewParentEntity.OptionsView.ShowPreview = False
            End If
        Catch ex As Exception

        End Try

    End Sub
    Sub Save_GridViewParentEntityLayout()
        If GridViewParentEntity.RowCount > 0 Then
            'Console.WriteLine("grvwSelectionLayout-" & Now)
            'Das aktuelle Layout speichern
            Dim XMLPath = System.IO.Path.Combine(Application.UserAppDataPath(), GridControlParentEntity.Name & "-CONSTRUCT-" & CONSTRUCTORID & "-UserLayout.xml")
            GridControlParentEntity.MainView.SaveLayoutToXml(XMLPath)
            tslblStatusMain_show(True, "Datagrid-Layout Selection saved")
        End If
    End Sub
    Private Function GetSelectionGridName()
        Return System.IO.Path.Combine(Application.UserAppDataPath(), GridControlSelection.Name & "-" & ACT_EBENE_STRING & "-" & CONSTRUCTORID & "-UserLayout.xml")
    End Function
    'Sub CreateTile(entity As Integer, Text As String)
    '    Dim tileitem As New DevExpress.XtraEditors.TileItem
    '    tileitem.Text = Text
    '    Dim colorBackground As Color
    '    Dim colorBorder As Color
    '    Dim style As FontStyle = FontStyle.Bold
    '    Dim Segoe As Font = New Font(New FontFamily("Tahoma"), 8, style)
    '    tileitem.TextAlignment = DevExpress.XtraEditors.TileItemContentAlignment.MiddleCenter
    '    tileitem.Tag = CURRENT_RECORD_ID
    '    Select Case entity
    '        Case 1
    '            tileitem.ItemSize = DevExpress.XtraEditors.TileItemSize.Wide
    '            tileitem.AppearanceItem.Normal.ForeColor = Color.Black
    '            colorBackground = Color.DeepSkyBlue
    '            colorBorder = Color.LightSkyBlue
    '        Case 2
    '            tileitem.ItemSize = DevExpress.XtraEditors.TileItemSize.Medium
    '            tileitem.AppearanceItem.Normal.ForeColor = Color.Black
    '            colorBackground = Color.Goldenrod
    '            colorBorder = Color.Gold
    '        Case 3
    '            tileitem.ItemSize = DevExpress.XtraEditors.TileItemSize.Medium
    '            colorBackground = Color.DarkViolet
    '            colorBorder = Color.Plum
    '    End Select
    '    tileitem.AppearanceItem.Normal.Font = Segoe

    '    tileitem.AppearanceItem.Normal.BackColor = colorBackground
    '    tileitem.AppearanceItem.Normal.BorderColor = colorBorder
    '    TileControl1.Groups(0).Items.Add(tileitem)



    'End Sub
    Sub Create_NavButton(entity As Integer, Text As String)
        Dim btn As New Button
        btn.FlatStyle = FlatStyle.Flat
        btn.Text = Text
        btn.Size = New Size(245, 42)
        Dim colorBackground As Color
        Dim colorBorder As Color
        Dim style As FontStyle = FontStyle.Bold
        Dim Segoe As Font = New Font(New FontFamily("Tahoma"), 9, style)
        btn.Font = Segoe
        btn.Tag = CURRENT_RECORD_ID

        Select Case entity
            Case 1
                btn.Name = "btnEntity" & entity
                '   tileitem.AppearanceItem.Normal.ForeColor = Color.Black
                colorBackground = Color.DeepSkyBlue
                colorBorder = Color.LightSkyBlue
            Case 2
                btn.Name = "btnEntity" & entity
                '  tileitem.ItemSize = DevExpress.XtraEditors.TileItemSize.Medium
                ' tileitem.AppearanceItem.Normal.ForeColor = Color.Black
                colorBackground = Color.Goldenrod
                colorBorder = Color.Gold
            Case 3
                btn.Name = "btnEntity" & entity
                'tileitem.ItemSize = DevExpress.XtraEditors.TileItemSize.Medium
                colorBackground = Color.DarkViolet
                colorBorder = Color.Plum
        End Select
        btn.BackColor = colorBackground
        btn.FlatAppearance.BorderColor = colorBorder

        pnlNavButtons.Controls.Add(btn)
        Select Case entity
            Case 1
                btn.Location = New Point(12, 2)
            Case 2
                btn.Location = New Point(263, 2)
            Case 3
                btn.Location = New Point(514, 2)
                btn.ForeColor = Color.White
        End Select
    End Sub
    Private Sub Anzeige_Selected_Entity()
        Try
            'Me.tslblEntity1.Visible = False
            'Me.tslblEntity2.Visible = False
            'Me.tslblEntity3.Visible = False
            tslblEntity.Text = ""
            'TileControl1.Groups(0).Items.Clear()
            Select Case ACT_EBENE
                Case 1
                    tslblEntity.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT
                    'tslblEntity1.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT
                    'Me.tslblEntity1.Visible = True
                    pnlNavButtons.Controls.Clear()
                    Create_NavButton(1, EBENE1_GRID_RESULT)
                Case 2
                    If CURRENT_FORM_TYPE = 5 Then
                        tslblEntity.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT & " #### Gruppen-Entität: " & EBENE2_ENTITY
                        'tslblEntity1.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT
                        'tslblEntity2.Text = "Gruppen-Entität: " & EBENE2_ENTITY
                        'Me.tslblEntity1.Visible = True
                        'Me.tslblEntity2.Visible = True
                        pnlNavButtons.Controls.Clear()
                        Create_NavButton(1, EBENE1_GRID_RESULT)
                        Create_NavButton(2, EBENE2_ENTITY)

                        Exit Sub
                    End If
                    If EBENE1_GRID_RESULT Is Nothing = False Then
                        tslblEntity.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT & " #### " & EBENE2_ENTITY & " - " & EBENE2_GRID_RESULT
                        'tslblEntity1.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT
                        pnlNavButtons.Controls.Clear()
                        Create_NavButton(1, EBENE1_GRID_RESULT)
                        Create_NavButton(2, EBENE2_GRID_RESULT)


                        'Me.tslblEntity1.Visible = True
                        'Me.tslblEntity2.Visible = True
                    Else
                        ' tslblEntity1.Text = EBENE2_ENTITY & " - " & EBENE2_GRID_RESULT
                        tslblEntity.Text = EBENE2_ENTITY & " - " & EBENE2_GRID_RESULT
                        'Me.tslblEntity1.Visible = True
                        Create_NavButton(1, EBENE2_GRID_RESULT)
                    End If
                Case 3
                    If CURRENT_FORM_TYPE = 5 Then
                        'tslblEntity1.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT
                        'tslblEntity2.Text = EBENE2_ENTITY & " - " & EBENE2_GRID_RESULT
                        'tslblEntity3.Text = "Gruppen-Entität: " & EBENE3_GRID_RESULT
                        pnlNavButtons.Controls.Clear()
                        Create_NavButton(1, EBENE1_GRID_RESULT)
                        Create_NavButton(2, EBENE2_ENTITY)
                        Create_NavButton(3, EBENE3_ENTITY)

                        'Me.tslblEntity1.Visible = True
                        'Me.tslblEntity2.Visible = True
                        'Me.tslblEntity3.Visible = True
                        Exit Sub
                    End If
                    If EBENE1_GRID_RESULT Is Nothing = False Then
                        'tslblEntity1.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT
                        'tslblEntity2.Text = EBENE2_ENTITY & " - " & EBENE2_GRID_RESULT
                        'tslblEntity3.Text = EBENE3_ENTITY & " - " & EBENE3_GRID_RESULT
                        tslblEntity.Text = EBENE1_ENTITY & " - " & EBENE1_GRID_RESULT & " #### " & EBENE2_ENTITY & " - " & EBENE2_GRID_RESULT & _
                             " #### " & EBENE3_ENTITY & " - " & EBENE3_GRID_RESULT
                        'Me.tslblEntity1.Visible = True
                        'Me.tslblEntity2.Visible = True
                        'Me.tslblEntity3.Visible = True
                        pnlNavButtons.Controls.Clear()
                        Create_NavButton(1, EBENE1_GRID_RESULT)
                        Create_NavButton(2, EBENE2_GRID_RESULT)
                        Create_NavButton(3, EBENE3_GRID_RESULT)


                    Else
                        'tslblEntity1.Text = EBENE2_ENTITY & " - " & EBENE2_GRID_RESULT
                        'tslblEntity2.Text = EBENE3_ENTITY & " - " & EBENE3_GRID_RESULT
                        tslblEntity.Text = EBENE2_ENTITY & " - " & EBENE2_GRID_RESULT & " #### " & EBENE3_ENTITY & " - " & EBENE3_GRID_RESULT
                        ' Me.tslblEntity1.Visible = True
                        'Me.tslblEntity2.Visible = True
                        pnlNavButtons.Controls.Clear()
                        Create_NavButton(1, EBENE2_GRID_RESULT)
                        Create_NavButton(2, EBENE3_GRID_RESULT)

                    End If
            End Select

        Catch ex As Exception
            MsgBox("Error in Anzeige_Selected_Entity:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub CreateColumns(ByVal tl As TreeList)
        ' Create three columns.
        tl.Columns.Clear()
        tl.BeginUpdate()
        tl.Columns.Add()
        tl.Columns(0).Caption = "Entität"
        tl.Columns(0).VisibleIndex = 0
        tl.Columns.Add()
        tl.Columns(1).Caption = "Record-ID"
        tl.Columns(1).VisibleIndex = 1
        tl.Columns.Add()
        tl.EndUpdate()
    End Sub
    Private Sub CreateNodes(ByVal tl As TreeList)
        tl.BeginUnboundLoad()
        ' Create a root node .
        Dim parentForRootNodes As TreeListNode = Nothing
        Dim rootNode As TreeListNode = tl.AppendNode(New Object() {"Format", "4711"}, parentForRootNodes)
        ' Create a child node for the node1            
        tl.AppendNode(New Object() {"Produktion", "66"}, rootNode)
        ' Creating more nodes
        ' ...
        tl.EndUnboundLoad()
    End Sub
    Sub Drag_Enter(e As DragEventArgs)
        If act_FormViewID <> 0 Then
            ClassDragDrop.Drag_enter(e)
        End If
    End Sub
    Sub Drag_Drop(e As DragEventArgs)
        If act_FormViewID <> 0 Then
            ClassDragDrop.Drop_File(e)
            Check_Dropped_Files(act_FormViewID)
        End If
    End Sub
    Private Sub GridControlSelection_DragDrop(sender As Object, e As DragEventArgs) Handles GridControlSelection.DragDrop
        Drag_Drop(e)
    End Sub

    Private Sub GridControlSelection_DragEnter(sender As Object, e As DragEventArgs) Handles GridControlSelection.DragEnter
        Drag_Enter(e)
    End Sub
    Private Sub pnlDetails_DragEnter(sender As Object, e As DragEventArgs) Handles pnlDetails.DragEnter
        Drag_Enter(e)
    End Sub

    Private Sub pnlDetails_DragDrop(sender As Object, e As DragEventArgs) Handles pnlDetails.DragDrop
        Drag_Drop(e)
    End Sub
    Private Sub ClearAllFiltersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ClearAllFiltersToolStripMenuItem.Click
        grvwSelection.ClearColumnsFilter()
        grvwSelection.ClearGrouping()
        grvwSelection.ClearSelection()
    End Sub

 
    Private Sub Check_Record_Changed()
        If EDIT_STATE <> "none" Then
            tslblStatusMain_show(False, "")
            EDIT_STATE = "none"
        End If

        If RECORD_CHANGED = True Then
            Dim result As DialogResult = MessageBox.Show("Sie haben ungespeicherte Änderungen. Wollen Sie diese speichern?", "Ungespeicherte Änderungen", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = Windows.Forms.DialogResult.Yes Then
                If CtrlCommandUI.IsInsert = True Then
                    EDIT_STATE = "none"
                    Me.pnlDetails.Enabled = False
                    CtrlCommandUI.IsInsert = False
                End If
                Update_Record_OnChange()
            End If
            RECORD_CHANGED = False
        End If
    End Sub

    Private Sub grvwSelection_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles grvwSelection.FocusedRowChanged
        If vFormClosing = True Or SaveRoutine_Active = True Then
            Exit Sub
        End If

        Check_Record_Changed()

        If dataloaded = True Then
            If LogErrorsOnly = False Then ClassLogger.Add(">> grvwSelection_FocusedRowChanged - EditState: " & EDIT_STATE, False)
            Dim selRecID = GetSelected_RecordID()
            If Not selRecID Is Nothing And selRecID <> SelectedRecordID Or EDIT_STATE = "insert" Then
                Focused_Row_Column_Changed()
            Else
                'Console.WriteLine("SelRecordID identisch")
            End If
        End If
    End Sub
    Private Sub grvwSelection_FocusedColumnChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs) Handles grvwSelection.FocusedColumnChanged
        If vFormClosing = True Or SaveRoutine_Active = True Then
            Exit Sub
        End If
        If dataloaded = True Then
            If LogErrorsOnly = False Then ClassLogger.Add(">> grvwSelection_FocusedRowChanged - EditState: " & EDIT_STATE, False)
            Dim selRecID = GetSelected_RecordID()
            If Not selRecID Is Nothing And selRecID <> SelectedRecordID Then
                Focused_Row_Column_Changed()
            Else
                'Console.WriteLine("SelRecordID identisch")
            End If
        End If
    End Sub
    Sub Load_Record_Data()
        Select Case EDIT_STATE
            Case "none"
                'Ganz normalerDatensatzwechsel Wechsel
                SelectedRecord_ShowData("Record-ID")
                'Refresh_Treeview_SelectedData()
                tslblStatusMain_show(False, "")
            Case "insert"
                'Refresh_Treeview_SelectedData()
            Case "update"
                ' Refresh_Treeview_SelectedData()
        End Select
        Select Case TCDetails.SelectedTabPageIndex
            Case 0
                'Die Values in die Controls laden
                If EDIT_STATE = "none" Then
                    'TabPageDetails.Text = "Detaileingabe zu '" & ACT_EBENE_STRING & "' - Record(" & SelectedRecordID & ")"
                    'Die Daten auf dem Panel laden
                    ClassControlValues.LoadControlValuesNeu(SelectedRecordID, CURRENT_PARENTID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
                    ClassControlValues.LoadControlValuesList(SelectedRecordID, CURRENT_PARENTID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
                    'Load_Control_Values(CtrlBuilder.AllControls)
                    'Refresh_Treeview_SelectedData()
                    RECORD_CHANGED = False
                End If
            Case 1
                RUN_WD_SEARCH(WD_Suche, "RECORD")
            Case 2
                If FOLLOW_UPisActive = True Then Refresh_FollowUps()
        End Select
        DT_FU_Record = Nothing
        VerknüpfungenToolStripMenuItem.Enabled = True

        If FOLLOW_UPisActive = True Then Refresh_FollowUp_TabHeader()
        Refresh_CreatedChangedRecordByID(SelectedRecordID)
        Anzeige_Selected_Entity()
        Show_act_WFTask()
        Get_RecordCounts_Nodes()

        Refresh_TaskOverview()
    End Sub
    Sub Focused_Row_Column_Changed()
        If LogErrorsOnly = False Then ClassLogger.Add(">> grvwSelection_FocusedRowChanged Complete - RecordID: " & CURRENT_RECORD_ID, False)
        Load_Record_Data()
    End Sub
    Sub HideColumns()
        Dim SQL As String = "SELECT CONTROL_ID, CONTROL_COL_NAME, CONTROL_SHOW_COLUMN FROM VWPMO_CONTROL_SCREEN WHERE CONTROL_SHOW_COLUMN = 0 AND FORM_ID = " & CURRENT_FORM_ID
        Dim DT As DataTable = ClassDatabase.Return_Datatable(SQL)
        Dim cols As DevExpress.XtraGrid.Columns.GridColumnCollection = grvwSelection.Columns

        If DT.Rows.Count <> 0 Then
            ' Alle Spalten, die ausgeblendet werden sollten durchgehen und Visible = False
            For Each row As DataRow In DT.Rows
                Dim colname As String = row.Item("CONTROL_COL_NAME")
                Dim col As DevExpress.XtraGrid.Columns.GridColumn = grvwSelection.Columns.Item(colname)

                If Not IsNothing(col) Then
                    col.Visible = False
                End If
            Next
        End If

        ' FormID und RecordID immer ausblenden
        grvwSelection.Columns.Item("Record-ID").Visible = False
        grvwSelection.Columns.Item("Form-ID").Visible = False
    End Sub
    Function GetSelected_RecordID()
        Try
            If grvwSelection.Columns.Count = 0 Then
                Me.pnlDetails.Enabled = False
                Me.tsbtnshowWorkflowtasks.Enabled = False
                tsstatus_Detail_show(True, "Keine Columns in Grid")
                Return Nothing
            End If
            'Überhaupt Rows in Grid?
            If grvwSelection.RowCount > 0 Then
                Dim Grid_RecordID = grvwSelection.GetFocusedRowCellValue(grvwSelection.Columns("Record-ID"))
                If Grid_RecordID Is Nothing = False Then
                    Return Grid_RecordID
                Else
                    tsstatus_Detail_show(True, "Grid_RecordID konnte nicht gewählt werden!")
                    ClassLogger.Add(">> Grid_RecordID konnte nicht gewählt werden - SelectedRecord_ShowData", True)
                    Return Nothing
                End If
            Else
                Return Nothing
            End If
        Catch ex As Exception

        End Try
    End Function
    Private Sub TreeViewEbeneSelect_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeViewEbeneSelect.AfterSelect
        If FormLoaded = True Then
            Check_Record_Changed()
            Load_Data_for_TreeView()
        End If
    End Sub
    Sub Load_Data_for_TreeView()
        ACT_EBENE = 0
        If Not TreeViewEbeneSelect.SelectedNode Is Nothing Then
            Try
                Dim selnode As TreeNode = TreeViewEbeneSelect.SelectedNode
                If (selnode.Parent IsNot Nothing) Then
                    If (selnode.Parent.GetType() Is GetType(TreeNode)) Then
                        ACT_EBENE = 2

                        Dim pnode As TreeNode = selnode.Parent
                        If (pnode.Parent IsNot Nothing) Then
                            If (selnode.Parent.GetType() Is GetType(TreeNode)) Then
                                ACT_EBENE = 3
                            End If
                        End If

                    End If
                Else
                    ACT_EBENE = 1
                End If
            Catch ex As Exception
                MsgBox("Error in Get ACT_EBENE:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
            End Try
            If LogErrorsOnly = False Then ClassLogger.Add(">> Tag (FormID) After Select: " & TreeViewEbeneSelect.SelectedNode.Tag.ToString, False)
            Load_Entity_Data(TreeViewEbeneSelect.SelectedNode.Tag)
        End If
    End Sub
    Private Function GET_GROUP_RECORD()
        Dim sqlRecord As String = "SELECT RECORD2_ID FROM TBPMO_RECORD_CONNECT WHERE RECORD1_ID = " & CURRENT_PARENTID

        Dim recid = ClassDatabase.Execute_Scalar(sqlRecord, True)
        If IsNothing(recid) Then
            If ClassControlCommandsUI.CreateRecord(CURRENT_FORM_ID) = True Then
                recid = ClassControlCommandsUI.GetLastRecord
                If Not IsNothing(recid) Then
                    'Die neue Record-ID setzen
                    CURRENT_RECORD_ID = recid
                    ClassControlCommandsUI.ConnectRecord(CURRENT_PARENTID, CURRENT_RECORD_ID, "Group-Entity Link")
                Else
                    Return False
                End If
            Else

                Return False
            End If
        Else
            Try
                CURRENT_RECORD_ID = CInt(recid)

            Catch ex As Exception
                MsgBox("Error while getting CURRENT_RECORDID: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                Return False
            End Try
        End If
        Dim SQL1 As String = "SELECT COUNT(*) FROM TBPMO_RECORD_CONNECT WHERE RECORD1_ID = " & CURRENT_PARENTID & " AND RECORD2_ID = " & CURRENT_RECORD_ID

        If ClassDatabase.Execute_Scalar(SQL1) = 0 Then
            ClassControlCommandsUI.ConnectRecord(CURRENT_PARENTID, CURRENT_RECORD_ID)
        End If
        Refresh_CreatedChangedRecordByID(CURRENT_RECORD_ID)
        Return True
    End Function

    Sub Load_Entity_Data(FORM_ID As Integer)
        Try
            Me.Cursor = Cursors.WaitCursor
            VerknüpfungenToolStripMenuItem.Enabled = False
            CURRENT_RECORD_ID = 0
            Dim IS_SINGLE_RECORD As Boolean
            Dim LOAD_DIRECT As Boolean
            VerknüpfungenToolStripMenuItem.Enabled = False
            CURRENT_FORM_TYPE = ClassDatabase.Execute_Scalar("SELECT FORM_TYPE_ID FROM TBPMO_FORM WHERE GUID = " & FORM_ID)
            IS_SINGLE_RECORD = ClassDatabase.Execute_Scalar("SELECT SINGLE_RECORD FROM TBPMO_FORM WHERE GUID = " & FORM_ID)
            LOAD_DIRECT = ClassDatabase.Execute_Scalar("SELECT LOAD_DIRECT FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID)
            SelectedRecordID = 0
            Dim DT As DataTable
            Dim sql As String = "SELECT PARENT_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID
            Dim PARENT_ID = ClassDatabase.Execute_Scalar(sql)
            If PARENT_ID Is Nothing Then
                MsgBox("Error in GetParentID for selectedNode - Check Logfile", MsgBoxStyle.Exclamation)
                Exit Sub
            End If
            dataloaded = False
            'Abhängig von der Entität die Selektierungs-Daten laden
            Dim _sql As String
            Select Case ACT_EBENE
                Case 1
                    CURRENT_PARENTID = 0
                    EBENE1_ENTITY = TreeViewEbeneSelect.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE1_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Ebene 1 in TreeView selektiert", False)
                    EBENE2_ENTITY = ""
                    EBENE3_ENTITY = ""
                    'tslblEntity2.Visible = False
                    'tslblEntity3.Visible = False

                    EBENE1_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID)
                    EBENE2_COLUMNNAME = ""
                    EBENE3_COLUMNNAME = ""
                    EBENE2_GRID_RESULT = Nothing
                    EBENE3_GRID_RESULT = Nothing
                    _sql = ClassDatabase.Execute_Scalar("SELECT SQL_SELECT_EBENE1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID)
                    If ClassControlCommands.CTRL_EXISTSinPARENT("btnEntity2", pnlNavButtons) Then
                        Dim btn As Button = DirectCast(pnlNavButtons.Controls("btnEntity2"), Button)
                        pnlNavButtons.Controls.Remove(btn)
                    End If
                    If ClassControlCommands.CTRL_EXISTSinPARENT("btnEntity3", pnlNavButtons) Then
                        Dim btn As Button = DirectCast(pnlNavButtons.Controls("btnEntity3"), Button)
                        pnlNavButtons.Controls.Remove(btn)
                    End If
                    If ClassControlCommands.CTRL_EXISTSinPARENT("btnEntity1", pnlNavButtons) Then
                        Dim btn As Button = DirectCast(pnlNavButtons.Controls("btnEntity1"), Button)
                        pnlNavButtons.Controls.Remove(btn)
                    End If
                    'Try
                    '    Dim tileitem As DevExpress.XtraEditors.TileItem = TileControl1.Groups(0).Items(1)
                    '    TileControl1.Groups(0).Items.Remove(tileitem)
                    'Catch ex As Exception

                    'End Try

                Case 2
                    Dim Level1Select = ClassDatabase.Execute_Scalar("SELECT LEVEL1_SELECT FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID)
                    If CBool(Level1Select) = False And CURRENT_FORM_TYPE <> 5 And EBENE1_RECID = 0 Then
                        MsgBox("Entität '" & TreeViewEbeneSelect.SelectedNode.Text & "' kann nicht ohne Auswahl eines Ebene 1 Datensatzes gewählt werden!", MsgBoxStyle.Exclamation)
                        TreeViewEbeneSelect.SelectedNode = TreeViewEbeneSelect.SelectedNode.Parent
                        Exit Sub
                    End If
                    EBENE2_ENTITY = TreeViewEbeneSelect.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE2_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Ebene 2 in TreeView selektiert", False)
                    EBENE3_ENTITY = ""
                    'Parent-ID setzen
                    If EBENE1_RECID > 0 Then
                        CURRENT_PARENTID = EBENE1_RECID
                    End If
                    'tslblEntity3.Visible = False
                    Select Case CURRENT_FORM_TYPE
                        Case 5
                            If GET_GROUP_RECORD() = True Then
                                EBENE2_RECID = CURRENT_RECORD_ID
                            End If
                    End Select

                    EBENE2_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID)

                    EBENE3_COLUMNNAME = ""
                    'Wenn bereits ein Record für Ebene 1 gewählt wurde dann einschränken
                    If EBENE1_RECID > 0 Then
                        _sql = ClassDatabase.Execute_Scalar("SELECT SQL_SELECT_EBENE2 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID)
                        _sql = _sql.Replace("@RecordID", EBENE1_RECID)
                    Else
                        _sql = ClassDatabase.Execute_Scalar("SELECT SQL_SELECT_EBENE1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID)
                    End If
                    EBENE2_GRID_RESULT = Nothing
                    EBENE3_GRID_RESULT = Nothing

                    Try
                        If ClassControlCommands.CTRL_EXISTSinPARENT("btnEntity3", pnlNavButtons) Then
                            Dim btn As Button = DirectCast(pnlNavButtons.Controls("btnEntity3"), Button)
                            pnlNavButtons.Controls.Remove(btn)
                        End If
                        If ClassControlCommands.CTRL_EXISTSinPARENT("btnEntity2", pnlNavButtons) Then
                            Dim btn As Button = DirectCast(pnlNavButtons.Controls("btnEntity2"), Button)
                            pnlNavButtons.Controls.Remove(btn)
                        End If
                    Catch ex As Exception

                    End Try

                Case 3
                    'Parent-ID setzen
                    If EBENE2_RECID > 0 Then
                        CURRENT_PARENTID = EBENE2_RECID
                    End If
                    Select Case CURRENT_FORM_TYPE
                        Case 5
                            If GET_GROUP_RECORD() = True Then
                                EBENE3_RECID = CURRENT_RECORD_ID
                            End If
                    End Select

                    If EBENE2_RECID = 0 Then
                        MsgBox("Entität '" & TreeViewEbeneSelect.SelectedNode.Text & "' kann nicht ohne Auswahl eines Ebene 1 Datensatzes gewählt werden!", MsgBoxStyle.Exclamation)
                        TreeViewEbeneSelect.SelectedNode = TreeViewEbeneSelect.SelectedNode.Parent
                        Exit Sub
                    End If

                    EBENE3_ENTITY = TreeViewEbeneSelect.SelectedNode.Text
                    ACT_EBENE_STRING = EBENE3_ENTITY
                    If LogErrorsOnly = False Then ClassLogger.Add(">> Ebene 3 in TreeView selektiert", False)
                    'Parent-ID setzen
                    If EBENE2_RECID > 0 Then
                        CURRENT_PARENTID = EBENE2_RECID
                    End If

                    EBENE3_COLUMNNAME = ClassDatabase.Execute_Scalar("SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID)
                    'Wenn bereits ein Record für Ebene 1 gewählt wurde dann eisnchränken
                    If EBENE2_RECID > 0 Then
                        Try
                            _sql = ClassDatabase.Execute_Scalar("SELECT SQL_SELECT_EBENE2 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID, True)
                            _sql = _sql.Replace("@RecordID", EBENE2_RECID)
                        Catch ex As Exception

                        End Try

                    Else
                        MsgBox("Entität kann nicht ohne Auswahl eines Ebene 2 Datensatzes gewählt werden!", MsgBoxStyle.Exclamation)
                        'Grid leeren
                        GridControlSelection.DataSource = Nothing
                        grvwSelection.Columns.Clear()
                        Me.Cursor = Cursors.Default
                        Exit Sub
                    End If
                    EBENE3_GRID_RESULT = Nothing
                Case 4

            End Select

            CURRENT_FORM_ID = FORM_ID
            CURRENT_ENTITYSTRING = ACT_EBENE_STRING
            act_FormViewID = ClassDatabase.Execute_Scalar("SELECT GUID FROM TBPMO_FORM_VIEW where FORM_ID = " & FORM_ID)
            If EDIT_STATE = "none" Then
                'Die Controls der Entität laden
                Load_Controls(act_FormViewID)
                set_pnlsize()
            End If
            CURRENT_FORMVIEW_ID = act_FormViewID

            'Überprüfen ob windream Dos angezeigt werden sollen?
            Check_windream_Show(act_FormViewID)



            If windream_Docshow = True Then
                Clear_Windream_ResultList()
                If WD_ShowEnitityDocs = True Then
                    RUN_WD_SEARCH("", "ENTITY")
                End If
            End If

            Me.pnlDetails.Enabled = False
            Me.tsbtnshowWorkflowtasks.Enabled = False
            tsbtnRecordAdd.Enabled = True


            Select Case CURRENT_FORM_TYPE
                Case 5
                    'Nur eine Gruppen-Entität: d.h. es wird nur die Dateientab angezeigt
                    Console.WriteLine("OnlyGroupType")

                    TabPageDetails.PageVisible = False
                    Anzeige_Selected_Entity()
                    tsbtnRecordAdd.Visible = False
                    tsbtnRecorddelete.Visible = False
                    tsbtnRecordSave.Visible = False
                    '   MsgBox(CURRENT_RECORD_ID)

                Case Else
                    tsbtnRecordAdd.Visible = True
                    tsbtnRecorddelete.Visible = True
                    tsbtnRecordSave.Visible = True
                    TabPageDetails.PageVisible = True
                    Dim Beschreibung = ClassDatabase.Execute_Scalar("SELECT FORM_TITLE FROM TBPMO_FORM_VIEW WHERE GUID = " & act_FormViewID)
                    'TabPageDetails.Text = "Detaileingabe zu " & Beschreibung
                    'Den Spaltennamen für die Selektion laden
                    sql = "SELECT COLUMN_NAME1 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & FORM_ID
                    'Jetzt die Datensätze zur Entität laden
                    CURRENT_ENTITYSQL = _sql
                    Dim DTEntity As DataTable = ClassDatabase.Return_Datatable(CURRENT_ENTITYSQL, "LoadEntityData - Get DTEntity")
                    Dim primaryKey(1) As DataColumn
                    primaryKey(0) = DTEntity.Columns("Record-ID")
                    DTEntity.PrimaryKey = primaryKey
                    LoadGrid_Selection(_sql, DTEntity)

                    If LOAD_DIRECT = True Or IS_SINGLE_RECORD = True Then
                        Dim sql1 = CURRENT_ENTITYSQL
                        sql1.Replace("T.*", "TOP 1 [Record-ID]")
                        Dim id = ClassDatabase.Execute_Scalar(sql1, True)
                        If Not id Is Nothing Then
                            If LogErrorsOnly = False Then ClassLogger.Add(">> Load Record directly - RecordID: " & CURRENT_RECORD_ID, False)
                            Load_Record_Data()
                        End If
                    End If
                        'Überprüfen ob es für diese Entität Wiedervorlagen gibt?
                        Check_FOLLOWUP_IsConfigured(CURRENT_FORM_ID)
            End Select

            Load_Templates()

            Me.Cursor = Cursors.Default
            dataloaded = True
        Catch ex As Exception
            MsgBox("Error in Load_Entity_Data:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub
    Sub Get_RecordCounts_Nodes()
        Try
            Dim selnode As TreeNode = TreeViewEbeneSelect.SelectedNode
            Dim a As Integer = 0
            For Each childNodeLevel1 As TreeNode In selnode.Nodes
                Dim PARENT_ID As Integer
                Dim TYPE_ID As Integer
                If a = 0 Then
                    Dim sql As String = "SELECT PARENT_ID, FORM_TYPE_ID FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & childNodeLevel1.Tag
                    Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, "ShowNodeAmounts")
                    PARENT_ID = DT.Rows(0).Item(0)
                    TYPE_ID = DT.Rows(0).Item(1)
                End If
                If TYPE_ID <> 5 Then
                    If childNodeLevel1.Text = "Allgemein" Then
                        Console.WriteLine("Allgemein-Reiter")
                    End If
                    Dim result As Integer = ReturnAmountofRecords(childNodeLevel1.Tag, PARENT_ID)
                    If result <> 99999999 Then
                        Dim origtext As String = childNodeLevel1.Text
                        If origtext.Contains(" (") Then
                            Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)
                            childNodeLevel1.Text = existingstring & " (" & result.ToString & ")"
                        Else
                            childNodeLevel1.Text = childNodeLevel1.Text & " (" & result.ToString & ")"
                        End If
                    End If

                    For Each childNodeLevel2 As TreeNode In childNodeLevel1.Nodes
                        Dim origtext As String = childNodeLevel2.Text
                        If origtext.Contains(" (") Then
                            Dim existingstring = origtext.Substring(0, origtext.IndexOf("(") - 1)
                            childNodeLevel2.Text = existingstring
                        End If
                        For Each childNodeLevel3 As TreeNode In childNodeLevel2.Nodes
                            Dim origtext1 As String = childNodeLevel3.Text
                            If origtext1.Contains(" (") Then
                                Dim existingstring = origtext1.Substring(0, origtext1.IndexOf("(") - 1)
                                childNodeLevel1.Text = existingstring
                            End If
                        Next
                    Next
                    a += 1
                End If

            Next
        Catch ex As Exception
            MsgBox("Error in Get_RecordCounts_Nodes:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub
    Function ReturnAmountofRecords(EntityID As Integer, PARENT_ID As Integer)
        Dim _sql As String
        'Abhängig von der Entität dieAnzahl der Datensätze laden
        _sql = ClassDatabase.Execute_Scalar("SELECT SQL_SELECT_EBENE2 FROM VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & EntityID)
        Select Case ACT_EBENE
            Case 1
                If EBENE1_RECID = 0 Then
                    Return 99999999
                End If

                _sql = _sql.Replace("@RecordID", EBENE1_RECID)
            Case 2
                If EBENE2_RECID = 0 Then
                    Return 99999999
                End If
                If EBENE1_RECID = 0 Then

                End If
                _sql = _sql.Replace("@RecordID", EBENE2_RECID)
            Case 3
                If EBENE3_RECID = 0 Then
                    Return 99999999
                End If
                _sql = _sql.Replace("@RecordID", EBENE2_RECID)

        End Select

        Dim DT2 As DataTable = ClassDatabase.Return_Datatable(_sql, "ReturnAmountofRecords 1")
        Return DT2.Rows.Count
    End Function
    Sub Load_Entity_Data_Only()
        Try
            Dim DTEntity As DataTable = ClassDatabase.Return_Datatable(CURRENT_ENTITYSQL, "Load_Entity_Data_Only")
            Dim primaryKey(1) As DataColumn
            primaryKey(0) = DTEntity.Columns("Record-ID")
            DTEntity.PrimaryKey = primaryKey

            LoadGrid_Selection(CURRENT_ENTITYSQL, DTEntity)
        Catch ex As Exception
            MsgBox("Error in Load_Entity_Data_Only:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub
    Sub Load_Templates()
        Try
            Dim sql As String = "SELECT * FROM VWPMO_TEMPLATE_ENTITY WHERE ENTITY_ID = " & CURRENT_FORM_ID & " ORDER BY TEMPLATE_NAME"
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, "Load_Templates")
            If Not IsNothing(DT) Then
                If DT.Rows.Count > 0 Then
                    VorlageToolStripMenuItem.Enabled = True
                    VorlageToolStripMenuItem.DropDownItems.Clear()
                    For Each row As DataRow In DT.Rows
                        Dim item As ToolStripMenuItem = VorlageToolStripMenuItem
                        Dim newItem As ToolStripMenuItem = New ToolStripMenuItem(row.Item("TEMPLATE_NAME").ToString, Nothing, AddressOf TemplateItem_Click)
                        newItem.Tag = row.Item("TEMPLATE_ID")
                        item.DropDownItems.Add(newItem) '                        subitem.DropDownItems.Add(newItem)
                    Next
                Else
                    VorlageToolStripMenuItem.Enabled = False
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in Load_Templates:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub TemplateItem_Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim TemplateID As Integer = Integer.Parse(item.Tag)
        If CURRENT_RECORD_ID > 0 Then
            Dim SOLLENTITY_ID = ClassDatabase.Execute_Scalar("SELECT ENTITY_ID FROM  VWPMO_TEMPLATE_ENTITY WHERE TEMPLATE_ID = " & TemplateID)
            Dim REC_ENTITY_ID = ClassDatabase.Execute_Scalar("SELECT FORM_ID FROM TBPMO_RECORD WHERE GUID = " & CURRENT_RECORD_ID)

            If Not IsNothing(SOLLENTITY_ID) Then
                If CInt(SOLLENTITY_ID) = REC_ENTITY_ID Then
                    Cursor = Cursors.WaitCursor
                    If ClassOfficeTemplate.Open_Word_Template(TemplateID, CURRENT_RECORD_ID) = True Then
                        RUN_WD_SEARCH(WD_Suche, "RECORD")
                        tslblStatusMain_show(True, "Vorlagen-Datei erfolgreich nach windream importiert!")
                    End If
                    Cursor = Cursors.Default
                Else
                    MsgBox("Bitte wählen Sie nochmal einen Datensatz aus!", MsgBoxStyle.Exclamation)
                End If
            End If
        Else
            MsgBox("Bitte wählen Sie zuerst einen Datensatz aus.", MsgBoxStyle.Exclamation)
        End If

       
    End Sub
    Private Sub grvwSelection_Layout(sender As Object, e As EventArgs) Handles grvwSelection.Layout
        If dataloaded = True Then
            If grvwSelection.RowCount > 0 Then
                'Console.WriteLine("grvwSelectionLayout-" & Now)
                'Das aktuelle Layout speichern
                Dim XMLPath = GetSelectionGridName()
                GridControlSelection.MainView.SaveLayoutToXml(XMLPath)
                tslblStatusMain_show(True, "Datagrid-Layout Selection saved")
            End If
        End If
    End Sub

    Private Sub frmForm_Constructor_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        Me.BringToFront()
        LoadLayouts()
        BindingNavigatorForm1.Visible = True
        Load_Level1()
    End Sub
    Private Sub ExportNachExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExportNachExcelToolStripMenuItem.Click
        Dim saveFileDialog1 As New SaveFileDialog
        saveFileDialog1.Filter = "Excel File|*.xlsx"
        saveFileDialog1.Title = "Export to Excel:"
        saveFileDialog1.ShowDialog()
        If saveFileDialog1.FileName <> "" Then
            Cursor = Cursors.WaitCursor
            grvwSelection.ExportToXlsx(saveFileDialog1.FileName)
            Dim result As MsgBoxResult
            result = MessageBox.Show("Datei wurde erstellt! Wollen Sie diese nun öffnen?", "Erfolgsmeldung:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result = MsgBoxResult.Yes Then
                Process.Start(saveFileDialog1.FileName)
            End If


        End If
        Cursor = Cursors.Default
    End Sub

    Private Sub TreeViewEbeneSelect_DragDrop(sender As Object, e As DragEventArgs) Handles TreeViewEbeneSelect.DragDrop

    End Sub

    Private Sub TreeViewEbeneSelect_DragEnter(sender As Object, e As DragEventArgs) Handles TreeViewEbeneSelect.DragEnter

    End Sub

    Private Sub WindreamSucheNeuLadenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles WindreamSucheNeuLadenToolStripMenuItem.Click
        RUN_WD_SEARCH(WD_Suche, "RECORD")
    End Sub

    Private Sub AnsichtKomplettZurücksetzenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AnsichtKomplettZurücksetzenToolStripMenuItem.Click
        Try
            Dim XMLPath = GetSelectionGridName()
            If File.Exists(XMLPath) Then
                Me.Cursor = Cursors.WaitCursor
                File.Delete(XMLPath)
                Load_Data_for_TreeView()
                tslblStatusMain_show(True, "Das Datagrid wurde erfolgreich zurückgesetzt - " & Now)
            End If
        Catch ex As Exception
            MsgBox("Error in GridSetBack:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
        Cursor = Cursors.Default
    End Sub

    Private Sub DateiimportEntitätToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DateiimportEntitätToolStripMenuItem.Click
        If CURRENT_PARENTID = 0 Then
            Exit Sub
        End If
        frmWD_EntityImport.ShowDialog()
    End Sub

    Private Sub KonfigurationToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles KonfigurationToolStripMenuItem.Click
        frmwindreamView_Config.ShowDialog()
    End Sub

    Private Sub AxObjectListControl_ItemClicked(sender As Object, e As EventArgs) Handles AxObjectListControl.ItemClicked
        CheckDocView()
    End Sub
    Sub CheckDocView()
        Dim _index = AxObjectListControl.GetFirstSelectedObject
        Dim path As String = AxObjectListControl.GetObjectPath(_index)
        path = path.Replace("?", vWLaufwerk)
        DocViewString = path

        If WD_ShowDocs = True Then
            CloseWDDocview()
            ShowDocView()
        End If
    End Sub
    Sub ShowDocView()
        Try
            CloseWDDocview()
            DocView = Nothing
            DocView = CreateObject("WMPViewXNG.Viewer")
            ' open the viewer
            DocView.ViewFile(DocViewString)
            OpenedFileString = DocViewString
        Catch ex As Exception
            MsgBox("Error in ShowDocView:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
      
    End Sub
    Sub CloseWDDocview()
        Try
            If DocView Is Nothing = False Then
                DocView.CloseView(OpenedFileString, 0)
            End If

        Catch ex As Exception
            ClassLogger.Add(" ### Error in CloseDocView")
            ClassLogger.Add("### " & ex.Message & " ###")
        End Try

    End Sub

    Private Sub WorkflowTasksAnneuErzeugenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles WorkflowTasksAnneuErzeugenToolStripMenuItem.Click
        Try
            Dim _MsgBoxResult As MsgBoxResult
            _MsgBoxResult = MessageBox.Show("Möchten Sie die Workflow-Tasks wirklich neu erzeugen lassen? Die alten Daten werden gelöscht!", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If _MsgBoxResult = MsgBoxResult.Yes Then
                Dim sql As String = "SELECT COUNT(*) FROM TBPMO_WORKFLOW_FORM where FORM_ID = @FORM_ID"
                sql = sql.Replace("@FORM_ID", CURRENT_FORM_ID)
                Dim result As Integer = ClassDatabase.Execute_Scalar(sql)
                If result > 0 Then
                    sql = "EXECUTE dbo.PRPMO_CREATE_WF_TASKS @FORM_ID, @RECORD_ID"
                    sql = sql.Replace("@FORM_ID", CURRENT_FORM_ID)
                    sql = sql.Replace("@RECORD_ID", CURRENT_RECORD_ID)
                    If ClassDatabase.Execute_non_Query(sql) = True Then
                        sql = "UPDATE TBPMO_WORKFLOW_TASK SET ACTIVE = 1, CHANGED_WHO = '@CHANGED_WHO' WHERE (RECORD_ID = '@RECORD_ID')"
                        sql = sql.Replace("@CHANGED_WHO", Environment.UserName)
                        sql = sql.Replace("@RECORD_ID", CURRENT_RECORD_ID)
                        If ClassDatabase.Execute_non_Query(sql) = True Then
                            Show_act_WFTask()
                        Else
                            MsgBox("Error during create WorkflowTask. Check Log", MsgBoxStyle.Exclamation)
                        End If
                    End If
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in Create WF-Tasks:" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation)
        End Try
    End Sub

    Private Sub CarouselToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles CarouselToolStripMenuItem.Click
        grvwCarousel.OptionsView.ViewMode = DevExpress.XtraGrid.Views.Layout.LayoutViewMode.Carousel
        GridControlSelection.MainView = grvwCarousel
    End Sub

    Private Sub TabelleToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles TabelleToolStripMenuItem.Click
        GridControlSelection.MainView = grvwSelection
    End Sub

    Private Sub ResetEbenenAuswahlToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ResetEbenenAuswahlToolStripMenuItem.Click
        ACT_EBENE = 0
        ACT_EBENE_STRING = ""
        EBENE1_ENTITY = ""
        EBENE1_RECID = 0
        EBENE2_ENTITY = ""
        EBENE2_RECID = 0
        EBENE3_ENTITY = ""
        EBENE3_RECID = 0
        BindingSourceEntity.DataSource = Nothing
        Load_TreeViewEbene()
    End Sub

    Private Sub grvwSelection_CalcRowHeight(sender As Object, e As RowHeightEventArgs) Handles grvwSelection.CalcRowHeight
        Dim datarow As System.Data.DataRowView = grvwSelection.GetRow(e.RowHandle)
        If Not IsNothing(datarow) Then
            Dim data() = datarow.Row.ItemArray

            For Each d In data
                If TypeOf d Is Byte() Then
                    e.RowHeight = 50
                End If
            Next
        End If
    End Sub

    Private Sub ZeigeRecordLogsToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ZeigeRecordLogsToolStripMenuItem.Click
        frmRecord_Changes.ShowDialog()
    End Sub
  

    Private Sub GridControlSelection_MouseEnter(sender As Object, e As EventArgs) Handles GridControlSelection.MouseEnter
        GridControlSelection.Select()
    End Sub

    Private Sub GridControlSelection_KeyDown(sender As Object, e As KeyEventArgs) Handles GridControlSelection.KeyDown
        MyBase.OnKeyDown(e)
        If e.Control AndAlso e.KeyCode = Keys.C Then
            If grvwSelection.GetRowCellValue(grvwSelection.FocusedRowHandle, grvwSelection.FocusedColumn) IsNot Nothing AndAlso grvwSelection.GetRowCellValue(grvwSelection.FocusedRowHandle, grvwSelection.FocusedColumn).ToString() <> String.Empty Then
                Clipboard.SetText(grvwSelection.GetRowCellValue(grvwSelection.FocusedRowHandle, grvwSelection.FocusedColumn).ToString())
                MsgBox("The value in the selected cell is null or empty!", MsgBoxStyle.Information)
            End If
        End If
    End Sub

    Private Sub TCDetails_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles TCDetails.SelectedPageChanged
        Select Case TCDetails.SelectedTabPageIndex
            Case 0
                If RECORD_NEEDS_REFRESH = True Then
                    ClassControlValues.LoadControlValuesNeu(SelectedRecordID, CURRENT_PARENTID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
                    ClassControlValues.LoadControlValuesList(SelectedRecordID, CURRENT_PARENTID, CURRENT_FORM_ID, CtrlBuilder.AllControls)
                    UpdRECORD_NEEDS_REFRESH(False)
                End If

                Refresh_CreatedChangedRecordByID(SelectedRecordID)
                RECORD_CHANGED = False
            Case 1 'windream-Dokumente finden
                If CURRENT_RECORD_ID = 0 Then
                    RUN_WD_SEARCH(WD_Suche, "ENTITY")
                Else
                    RUN_WD_SEARCH(WD_Suche, "RECORD")
                End If

            Case 2
                Refresh_FollowUps()
        End Select
    End Sub

    Private Sub pnlDetails_MouseClick(sender As Object, e As MouseEventArgs) Handles pnlDetails.MouseClick
        pnlDetails.Select()
        grvwSelection.Appearance.FocusedRow.BackColor = Color.OrangeRed
    End Sub

    Private Sub ListViewFollowUp_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListViewFollowUp.SelectedIndexChanged
        If Me.ListViewFollowUp.SelectedItems.Count > 0 Then
            FOLL_UP_ID = ListViewFollowUp.SelectedItems(0).Text
            lblFollowUp_save.Visible = False
            For Each DR As DataRow In DT_FU_ENTITY.Rows
                If FOLL_UP_ID = DR.Item("GUID") Then
                    grpbxFU_Profile.Enabled = True
                    dataloaded = False
                    FOLL_UP_DATE_CTRL_ID = DR.Item("DEPENDENT_DATE_CTRL_ID")
                    Dim datevalue = ClassControlValues.Get_Control_Value_for_ID(DR.Item("DEPENDENT_DATE_CTRL_ID"), CURRENT_RECORD_ID)
                    If Not IsNothing(datevalue) Then
                        FOLL_UP_RECORD_DEFINED = True
                        dtpWV.Value = CDate(datevalue)
                    Else
                        dtpWV.Value = CDate(Now)
                        FOLL_UP_RECORD_DEFINED = False
                    End If
                    Dim caption = ClassDatabase.Execute_Scalar("SELECT COL_NAME FROM TBPMO_CONTROL WHERE GUID = " & DR.Item("DEPENDENT_DATE_CTRL_ID"), True)
                    If Not IsNothing(caption) Then
                        lblWV_Date.Text = CStr(caption)
                    End If
                    FOLL_UP_DONE_CTRL_ID = DR.Item("DEPENDENT_DONE_CTRL_ID")
                    Dim checkvalue = ClassControlValues.Get_Control_Value_for_ID(DR.Item("DEPENDENT_DONE_CTRL_ID"), CURRENT_RECORD_ID)
                    If Not IsNothing(checkvalue) Then
                        chkFollowUp.Checked = CBool(checkvalue)
                    Else
                        chkFollowUp.Checked = False
                    End If
                    Dim captionCheck = ClassDatabase.Execute_Scalar("SELECT CONTROL_TEXT FROM TBPMO_CONTROL_SCREEN WHERE SCREEN_ID = 1 AND CONTROL_ID = " & DR.Item("DEPENDENT_DONE_CTRL_ID"), True)
                    If Not IsNothing(captionCheck) Then
                        chkFollowUp.Text = CStr(captionCheck)
                    End If

                    Load_FUUser(FOLL_UP_ID)

                    dataloaded = True
                End If
            Next
        End If
    End Sub
    Sub Load_FUUser(ID As Integer)
        Try
            Dim sql = "SELECT T.GUID, T1.USERNAME FROM TBPMO_FOLLUPEMAIL_RECORD T, TBDD_USER T1 WHERE T.USER_ID = T1.GUID AND T.FOLLOW_UP_ID = " & ID & " AND T.RECORD_ID = " & CURRENT_RECORD_ID & " ORDER BY T1.USERNAME"
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql, "Load_FollowUpUser")
            ListBoxUser2Profile.DataSource = DT
            ListBoxUser2Profile.DisplayMember = DT.Columns(1).ColumnName
            ListBoxUser2Profile.ValueMember = DT.Columns(0).ColumnName
        Catch ex As Exception
            MsgBox("Fehler bei Load_FUUser:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub dtpWV_ValueChanged(sender As Object, e As EventArgs) Handles dtpWV.ValueChanged
        If dataloaded = False Then
            Exit Sub
        End If
        If ClassControlCommandsUI.UpdateControlValue(FOLL_UP_DATE_CTRL_ID, CURRENT_RECORD_ID, dtpWV.Value) = True Then
            lblFollowUp_save.Text = "Wiedervorlage gespeichert - " & Now.ToString
            lblFollowUp_save.Visible = True
            UpdRECORD_NEEDS_REFRESH(True)
        Else
            lblFollowUp_save.Visible = False
            UpdRECORD_NEEDS_REFRESH(False)
        End If
    End Sub

    Private Sub chkFollowUp_CheckedChanged(sender As Object, e As EventArgs) Handles chkFollowUp.CheckedChanged
        If dataloaded = False Then
            Exit Sub
        End If
        If ClassControlCommandsUI.UpdateControlValue(FOLL_UP_DONE_CTRL_ID, CURRENT_RECORD_ID, chkFollowUp.Checked.ToString) = True Then
            lblFollowUp_save.Text = "Wiedervorlage gespeichert - " & Now.ToString
            lblFollowUp_save.Visible = True
            UpdRECORD_NEEDS_REFRESH(True)
        Else
            lblFollowUp_save.Visible = False
            UpdRECORD_NEEDS_REFRESH(False)
        End If
    End Sub
    Sub UpdRECORD_NEEDS_REFRESH(state As Boolean)
        If RECORD_NEEDS_REFRESH <> state Then
            RECORD_NEEDS_REFRESH = state
        End If
    End Sub
   
    Private Sub btnAddUser_WV_Click(sender As Object, e As EventArgs) Handles btnAddUser_WV.Click
        If cmbWHUser.SelectedIndex <> -1 And FOLL_UP_ID > 0 Then
            Try
                Dim ins = "INSERT INTO TBPMO_FOLLUPEMAIL_RECORD (FOLLOW_UP_ID,USER_ID,RECORD_ID,ADDED_WHO) VALUES (" & FOLL_UP_ID & ", " & cmbWHUser.SelectedValue & ", " & CURRENT_RECORD_ID & ", '" & Environment.UserName & "')"
                If ClassDatabase.Execute_non_Query(ins, True) = True Then
                    Load_FUUser(FOLL_UP_ID)
                End If
            Catch ex As Exception
                MsgBox("Fehler bei Add User 2 FollowUp_Record:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If
    End Sub

    Private Sub btndelete_Click(sender As Object, e As EventArgs) Handles btndelete.Click
        If ListBoxUser2Profile.SelectedIndex <> -1 Then
            Try
                Dim del = "DELETE FROM TBPMO_FOLLUPEMAIL_RECORD WHERE GUID = " & ListBoxUser2Profile.SelectedValue
                If ClassDatabase.Execute_non_Query(del, True) = True Then
                    Load_FUUser(FOLL_UP_ID)
                End If
            Catch ex As Exception
                MsgBox("Fehler bei Löschen Userverknüpfung:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If
    End Sub

    Private Sub VerknüpfungenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles VerknüpfungenToolStripMenuItem.Click
        Show_Verknuepfungen()
    End Sub
    Sub Show_Verknuepfungen()
        If SplitCont_Details.Collapsed = True Then
            VerknüpfungenToolStripMenuItem.Text = "Verknüfungen ausblenden"
            Load_ParentConnections()
            XtraTabControl1.SelectedTabPageIndex = 0
            SplitCont_Details.Collapsed = False
        Else
            VerknüpfungenToolStripMenuItem.Text = "Verknüfungen einblenden"
            SplitCont_Details.Collapsed = True
            Save_GridViewParentEntityLayout()
            My.Settings.Save()
        End If
    End Sub
    Sub Load_ParentConnections()
        Try
            ' SELECT COLUMN_NAME1 FROM VWTEMP_cPMO_FORM
            Dim DT As DataTable = ClassDatabase.Return_Datatable("SELECT TOP 1 PARENT_ID,FORM_TITLE from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & CURRENT_FORM_ID, "Parent-Data")
            Dim Parent_ID = DT.Rows(0).Item(0)
            Dim Title = DT.Rows(0).Item(1)
            Dim Colname = "[" & ClassDatabase.Execute_Scalar("SELECT TOP 1 COLUMN_NAME1 from VWPMO_CONSTRUCTOR_FORMS WHERE CONSTRUCT_ID = " & CONSTRUCTORID & " AND FORM_ID = " & Parent_ID, True) & "]"
            Load_GridViewParentEntity_Layout()
            If Not IsNothing(Parent_ID) And Not IsNothing(Colname) Then
                Dim sql = "select [Record-ID], " & Colname & " from VWTEMP_PMO_FORM" & Parent_ID.ToString
                Dim DTGrid As DataTable = ClassDatabase.Return_Datatable(sql, "VariableSelect ParentEntity")
                GridControlParentEntity.DataSource = Nothing
                GridViewParentEntity.Columns.Clear()
                'Databinding Neu
                GridControlParentEntity.DataSource = DTGrid
                TabPageParentEntity.Text = "Aktuelle Parent-Entity: " & Title
                GridViewParentEntity.Columns.Item("Record-ID").Visible = False
            End If
        Catch ex As Exception
            MsgBox("Fehler bei Load_ParentConnections:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub GridViewParentEntity_FocusedColumnChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedColumnChangedEventArgs) Handles GridViewParentEntity.FocusedColumnChanged
        GetFocusedParentID()
    End Sub

    Private Sub GridViewParentEntity_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles GridViewParentEntity.FocusedRowChanged
        GetFocusedParentID()
    End Sub
    Dim Linkparent_ID As Integer
    Sub GetFocusedParentID()
        Try
            If GridViewParentEntity.RowCount > 0 Then
                Dim Grid_RecordID = GridViewParentEntity.GetFocusedRowCellValue(GridViewParentEntity.Columns("Record-ID"))
                If Grid_RecordID Is Nothing = False Then
                    Linkparent_ID = Grid_RecordID
                    lblParentID.Text = Grid_RecordID.ToString & " - " & GridViewParentEntity.GetFocusedRowCellValue(GridViewParentEntity.Columns(1))
                    btnRefreshPEntity.BackColor = Color.DarkOrange
                    btnRefreshPEntity.FlatAppearance.BorderColor = Color.DarkOrange
                Else
                    ClassLogger.Add(">> Grid_RecordID konnte nicht gewählt werden - GetFocusedParentID", True)
                    lblParentID.Text = "keine Auswahl möglich"
                End If
            Else
                lblParentID.Text = "keine Rows gefunden"
            End If
        Catch ex As Exception
            MsgBox("Fehler bei GetFocusedParentID:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnRefreshPEntity_Click(sender As Object, e As EventArgs) Handles btnRefreshPEntity.Click
        If lblParentID.Text = "" Then
            Exit Sub
        End If
        If CURRENT_PARENTID > 0 Then
            Dim result As MsgBoxResult
            result = MessageBox.Show("Möchten Sie den Parent-Datensatz für den aktuellen Datensatz wirklich aktualisieren?", "Bestätigung erforderlich:", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
            If result <> MsgBoxResult.Yes Then
                Exit Sub
            Else
                If ClassDatabase.Execute_non_Query("DELETE FROM TBPMO_RECORD_CONNECT WHERE RECORD2_ID = " & CURRENT_RECORD_ID & " AND RECORD1_ID = " & CURRENT_PARENTID, True) = False Then
                    Exit Sub
                End If
            End If

        End If
        If ClassControlCommandsUI.ConnectRecord(Linkparent_ID, CURRENT_RECORD_ID, "ENTITY" & CURRENT_FORM_ID.ToString) = True Then
            Save_GridViewParentEntityLayout()
            MsgBox("Die Parent-Entität wurde erfolgreich aktualisiert!", MsgBoxStyle.Information)
            Check_Record_Changed()
            Load_Data_for_TreeView()
            btnRefreshPEntity.BackColor = Color.Lime
            btnRefreshPEntity.FlatAppearance.BorderColor = Color.Lime
            'Show_Verknuepfungen()
        End If
        'Dim PARENT_RECORD_ID = ClassDatabase.Execute_Scalar("SELECT GUID FROM TBPMO_RECORD_CONNECT WHERE ")

    End Sub

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