Imports DevExpress.XtraGrid.Views.Tile
Imports DevExpress.XtraEditors
Imports System.Text.RegularExpressions

Public Class frmConstructorDesigner
    Dim SELECTED_ENTITY_ID As Integer
    Dim SELECTED_CONSTRUCTOR_DETAIL_ID As Integer
    Dim formloaded As Boolean = False
    Dim AtPlaceholderPattern As String = "@[A-Za-z_]+"
    Private Sub TBPMO_FORM_CONSTRUCTORBindingNavigatorSaveItem_Click(sender As Object, e As EventArgs) Handles TBPMO_FORM_CONSTRUCTORBindingNavigatorSaveItem.Click
        Try
            Me.Validate()
            Me.TBPMO_FORM_CONSTRUCTORBindingSource.EndEdit()
            If DD_ECMAdmin.TBPMO_FORM_CONSTRUCTOR.GetChanges Is Nothing = False Then
                Me.CHANGED_WHOTextBox.Text = USER_USERNAME
                TBPMO_FORM_CONSTRUCTORTableAdapter.Update(DD_ECMAdmin.TBPMO_FORM_CONSTRUCTOR)
                lblSave.Visible = True
            Else
                lblSave.Visible = False
            End If

        Catch ex As Exception
            MsgBox("Error in Saving FormConstructor:" & vbNewLine & ex.Message)
        End Try


    End Sub

    Private Sub frmConstructorDesigner_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'TODO: Diese Codezeile lädt Daten in die Tabelle "DD_ECMAdmin1.TBPMO_FORM_CONSTRUCTOR". Sie können sie bei Bedarf verschieben oder entfernen.
        Try
            XtraTabControl2.SelectedTabPageIndex = 0
            formloaded = False
            Me.TBPMO_FORM_CONSTRUCTORTableAdapter.Connection.ConnectionString = MyConnectionString
            Me.TBPMO_FORM_CONSTRUCTOR_DETAILTableAdapter.Connection.ConnectionString = MyConnectionString
            Load_Head()
            Dim sql1 As String = "SELECT T.GUID, [dbo].[FNPMO_GETOBJECTCAPTION]('" & USER_LANGUAGE & "','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T1.GUID), 1) AS FORM_TITLE FROM TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.GUID = T1.FORM_ID AND T.SHOW_FORM_CONSTRUCT = 1 AND T1.SCREEN_ID = 1 ORDER BY T1.FORM_TITLE"
            Dim DTFORMS As DataTable = ClassDatabase.Return_Datatable(sql1)
            'FORM_IDComboBox.DataSource = DTFORMS
            'FORM_IDComboBox.DisplayMember = DTFORMS.Columns(1).ColumnName
            'FORM_IDComboBox.ValueMember = DTFORMS.Columns(0).ColumnName

            Dim sql2 As String = "SELECT T.GUID, [dbo].[FNPMO_GETOBJECTCAPTION]('" & USER_LANGUAGE & "','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), T1.GUID), 1) AS FORM_TITLE FROM TBPMO_FORM T, TBPMO_FORM_VIEW T1 WHERE T.FORM_TYPE_ID IN (1,2) AND T.GUID = T1.FORM_ID AND T.SHOW_FORM_CONSTRUCT = 1 AND T1.SCREEN_ID = 1 ORDER BY T1.FORM_TITLE"
            Dim DTParent As DataTable = ClassDatabase.Return_Datatable(sql2)
            'PARENT_IDComboBox.DataSource = DTParent
            'PARENT_IDComboBox.DisplayMember = DTParent.Columns(1).ColumnName
            'PARENT_IDComboBox.ValueMember = DTParent.Columns(0).ColumnName

        Catch ex As Exception
            MsgBox("Error Loading Form:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Sub Load_Head()
        Try
            Me.TBPMO_FORM_CONSTRUCTORTableAdapter.Fill(Me.DD_ECMAdmin.TBPMO_FORM_CONSTRUCTOR, USER_LANGUAGE, CURRENT_SCREEN_ID)
        Catch ex As Exception
            MsgBox("Error Loading Form:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub Load_Detail(ID As Integer)
        Try
            Me.TBPMO_FORM_CONSTRUCTOR_DETAILTableAdapter.Fill(Me.DD_ECMAdmin.TBPMO_FORM_CONSTRUCTOR_DETAIL, ID)
            SELECTED_ENTITY_ID = ClassDatabase.Execute_Scalar("SELECT FORM_ID FROM TBPMO_FORM_CONSTRUCTOR_DETAIL WHERE GUID = " & ID)
        Catch ex As System.Exception
            MsgBox("Error Loading Details:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            Exit Sub
        End Try
        Select Case XtraTabControl2.SelectedTabPageIndex
            Case 0
                Me.btnSetHeadline.Visible = False
                Load_QuickDisplay()
            Case 2
                RecordSearch_Config()
        End Select

    End Sub
    Public Sub Load_QuickDisplay()
        Try
            If SELECTED_CONSTRUCTOR_DETAIL_ID = 0 Then Exit Sub
            Dim formId = ClassDatabase.Execute_Scalar("SELECT FORM_ID FROM TBPMO_FORM_CONSTRUCTOR_DETAIL WHERE GUID = " & SELECTED_CONSTRUCTOR_DETAIL_ID)
            Dim sql = "SELECT T.GUID, T.COL_NAME AS 'COL_NAME' FROM TBPMO_CONTROL T, TBPMO_CONTROL_SCREEN T1, TBPMO_CONTROL_TYPE T2 WHERE T.SHOW_COLUMN = 1 AND T.[COL_NAME] <> '' AND T.GUID = T1.CONTROL_ID AND T.CONTROL_TYPE_ID = T2.GUID AND T.FORM_ID = " & formId & " AND LEN(ISNULL(T.COL_NAME,'')) > 0 and t.CONTROL_TYPE_ID not in (1,5,12) " & _
                                "AND T2.GUID not in (1,5,7,8,9) AND T.GUID NOT IN (SELECT CONTROL_ID FROM TBPMO_FORM_CONSTR_QUICK_DISPLAY WHERE CONSTRUCT_ID = " & SELECTED_CONSTRUCTOR_DETAIL_ID & ") ORDER BY T1.TAB_INDEX"
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            listBoxControls.DataSource = DT
            listBoxControls.DisplayMember = DT.Columns(1).ColumnName
            listBoxControls.ValueMember = DT.Columns(0).ColumnName

            Dim DT2 = ClassDatabase.Return_Datatable("SELECT T.GUID, T1.COL_NAME FROM TBPMO_FORM_CONSTR_QUICK_DISPLAY T, TBPMO_CONTROL T1 WHERE T1.CONTROL_TYPE_ID <> 6 AND T.CONTROL_ID = T1.GUID AND T.CONSTRUCT_ID = " & SELECTED_CONSTRUCTOR_DETAIL_ID & " ORDER BY T.SEQUENCE")
            ListBoxConfiguredDisplay.DataSource = DT2
            ListBoxConfiguredDisplay.DisplayMember = DT2.Columns(1).ColumnName
            ListBoxConfiguredDisplay.ValueMember = DT2.Columns(0).ColumnName

            Dim DT3 As DataTable = ClassDatabase.Return_Datatable("SELECT T.GUID, T1.COL_NAME FROM TBPMO_FORM_CONSTR_QUICK_DISPLAY T, TBPMO_CONTROL T1 WHERE T1.CONTROL_TYPE_ID = 6 AND T.CONTROL_ID = T1.GUID AND T.CONSTRUCT_ID = " & SELECTED_CONSTRUCTOR_DETAIL_ID)
            If DT3.Rows.Count = 1 Then
                Me.txtQuickViewPicture.Text = DT3.Rows(0).Item(1)
                Me.txtQuickViewPicture.Tag = DT3.Rows(0).Item(0)
            Else
                Me.txtQuickViewPicture.Text = "NOT CONFIGURED"
                Me.txtQuickViewPicture.Tag = Nothing
            End If
            Try
                Me.TBTEMP_QUICKDISPLAYTableAdapter.Connection.ConnectionString = MyConnectionString
                Me.TBTEMP_QUICKDISPLAYTableAdapter.Fill(Me.DD_DMSDataSet.TBTEMP_QUICKDISPLAY, SELECTED_CONSTRUCTOR_DETAIL_ID)
            Catch ex As System.Exception
                MsgBox("Error in Load_Preview_QuickDisplay:" & vbNewLine & ex.Message)
            End Try
        Catch ex As Exception
            MsgBox("Error Load_QuickDisplay:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Public Sub Load_ConstructorUser()
        Try
            Dim Sql = String.Format("SELECT * FROM TBDD_USER WHERE MODULE_RECORD_ORG = 1 AND GUID NOT IN (SELECT USER_ID FROM TBPMO_CONSTRUCTOR_USER WHERE CONSTRUCT_ID = {0}) ORDER By USERNAME", CONSTRUCTOR_IDTextBox.Text)
            Dim DT_USER = ClassDatabase.Return_Datatable(Sql)
            Sql = String.Format("SELECT T1.GUID, T.USERNAME + ' - ' + CASE T1.HOME_MENUE WHEN 1 THEN 'HOME' ELSE 'STANDARD' END AS USERNAME, T.EMAIL, T.NAME, T.PRENAME FROM TBDD_USER T, TBPMO_CONSTRUCTOR_USER T1 WHERE T1.USER_ID = T.GUID AND T1.CONSTRUCT_ID = {0} ORDER BY T.USERNAME", CONSTRUCTOR_IDTextBox.Text)
            Dim DT_USER_CONSTR As DataTable = ClassDatabase.Return_Datatable(Sql)
            Try
                DD_ECMAdmin.TBAD_Users.Clear()

                For Each row As DataRow In DT_USER.Rows
                    Dim newUserRow As DD_ECMAdmin.TBAD_UsersRow
                    newUserRow = DD_ECMAdmin.TBAD_Users.NewTBAD_UsersRow
                    newUserRow.Username = row.Item("USERNAME")
                    newUserRow.Surname = row.Item("NAME")
                    newUserRow.Prename = row.Item("PRENAME")
                    Try
                        newUserRow.Email = row.Item("EMAIL")
                    Catch ex As Exception
                        newUserRow.Email = ""
                    End Try

                    newUserRow.ID = row.Item("GUID")
                    DD_ECMAdmin.TBAD_Users.Rows.Add(newUserRow)
                    ' chklbxUserForGroup.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
                Next
            Catch ex As Exception
                MsgBox("Error Load_Users for menues:" & vbNewLine & ex.Message)
            End Try
           
            Try
                DD_ECMAdmin.TBWH_Users1.Clear()

                For Each row As DataRow In DT_USER_CONSTR.Rows
                    Dim newUserRow As DD_ECMAdmin.TBWH_Users1Row
                    newUserRow = DD_ECMAdmin.TBWH_Users1.NewTBWH_Users1Row
                    newUserRow.Surname = row.Item("NAME")
                    newUserRow.Prename = row.Item("PRENAME")
                    newUserRow.Username = row.Item("USERNAME")
                    Try
                        newUserRow.Email = row.Item("EMAIL")
                    Catch ex As Exception
                        newUserRow.Email = ""
                    End Try

                    newUserRow.ID = row.Item("GUID")
                    DD_ECMAdmin.TBWH_Users1.Rows.Add(newUserRow)
                    ' chklbxUserForGroup.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
                Next
            Catch ex As Exception
                MsgBox("Error loading Users for Constructor:" & vbNewLine & ex.Message)
            End Try
        Catch ex As Exception
            MsgBox("UnexpectedError Load_ConstructorUser:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Public Sub RecordSearch_Config()
        Try
            'Zurücksetzen
            lblSaveDocSearch.Visible = False

            Dim res = ClassDatabase.Execute_Scalar("SELECT DOCUMENT_VIEW FROM TBPMO_FORM_VIEW WHERE FORM_ID = " & SELECTED_ENTITY_ID & " and SCREEN_ID = " & CURRENT_SCREEN_ID)

            If res = True Then
                chkWDSearch_Active.Checked = True
            Else
                chkWDSearch_Active.Checked = False
            End If

            Dim DT As DataTable = ClassDatabase.Return_Datatable("SELECT DOC_SEARCH_TAB1,ACTIVATE_DOC_SEARCH_ON_EDIT FROM VWPMO_CONSTRUCTOR_FORMS WHERE GUID = " & SELECTED_CONSTRUCTOR_DETAIL_ID)
            res = DT.Rows(0).Item(0)
            If CBool(res) = True Then
                chkDOC_SEARCH_TAB1.Checked = True
            Else
                chkDOC_SEARCH_TAB1.Checked = False
            End If
            res = DT.Rows(0).Item(1)
            If CBool(res) = True Then
                chkActivateDSOnEdit.Checked = True
            Else
                chkActivateDSOnEdit.Checked = False
            End If
        Catch ex As Exception
            MsgBox("Error in RecordSearch_Config:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Private Sub frmConstructorDesigner_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        formloaded = True
        Load_TreeViewEbene()
        Load_ConstructorUser()
        LANGUAGETextBox.Text = USER_LANGUAGE
    End Sub
    Sub Load_TreeViewEbene()
        Try
            Dim CONSTR_ID As Integer = CONSTRUCTOR_IDTextBox.Text

            Dim sel_sql = String.Format("SELECT *, [dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), FORM_VIEW_ID), {1}) AS 'CAPTION' " & _
                            "from VWPMO_CONSTRUCTOR_FORMS WHERE FORM_TYPE_ID IN (1,4) AND PARENT_ID = 0 AND CONSTRUCT_ID = {2} AND SCREEN_ID = {3} ORDER BY SEQUENCE", USER_LANGUAGE, CURRENT_SCREEN_ID, CONSTR_ID, CURRENT_SCREEN_ID)

            Dim DT As DataTable = ClassDatabase.Return_Datatable(sel_sql)
            If DT.Rows.Count >= 1 Then
                TreeViewDetails.Nodes.Clear()
                For Each rowEbene0 As DataRow In DT.Rows
                    Dim Node As TreeNode
                    Node = TreeViewDetails.Nodes.Add("E1: " & rowEbene0.Item("CAPTION").ToString)
                    Node.Tag = rowEbene0.Item("GUID")
                    'Jetzt die Ebene1Knoten einhängen
                    sel_sql = String.Format("SELECT *, [dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), FORM_VIEW_ID), {1}) AS 'CAPTION' " & _
                            "from VWPMO_CONSTRUCTOR_FORMS WHERE FORM_TYPE_ID in (2,5) AND PARENT_ID = {2} AND CONSTRUCT_ID = {3} AND SCREEN_ID = {4} ORDER BY SEQUENCE", USER_LANGUAGE, CURRENT_SCREEN_ID, rowEbene0.Item("FORM_ID"), CONSTR_ID, CURRENT_SCREEN_ID)

                    Dim dtEbene1 As DataTable = ClassDatabase.Return_Datatable(sel_sql)
                    If dtEbene1.Rows.Count > 0 Then
                        For Each rowEbene1 As DataRow In dtEbene1.Rows
                            Dim Node1 As TreeNode
                            Node1 = Node.Nodes.Add("E2: " & rowEbene1.Item("CAPTION").ToString)
                            Node1.Tag = rowEbene1.Item("GUID")
                            'Jetzt die Ebene2 Knoten einhängen
                            sel_sql = String.Format("SELECT *, [dbo].[FNPMO_GETOBJECTCAPTION]('{0}','FORMVIEW_TITLE' + CONVERT(VARCHAR(5), FORM_VIEW_ID), {1}) AS 'CAPTION' " & _
                           "from VWPMO_CONSTRUCTOR_FORMS WHERE FORM_TYPE_ID in (3,5) AND PARENT_ID = {2} AND CONSTRUCT_ID = {3} AND SCREEN_ID = {4} ORDER BY SEQUENCE", USER_LANGUAGE, CURRENT_SCREEN_ID, rowEbene1.Item("FORM_ID"), CONSTR_ID, CURRENT_SCREEN_ID)

                            Dim dtEbene2 As DataTable = ClassDatabase.Return_Datatable(sel_sql)
                            If dtEbene2.Rows.Count > 0 Then
                                For Each rowEbene2 As DataRow In dtEbene2.Rows
                                    Dim Node2 As TreeNode
                                    Node2 = Node1.Nodes.Add("E3: " & rowEbene2.Item("CAPTION").ToString)
                                    Node2.Tag = rowEbene2.Item("GUID")
                                Next
                            End If

                        Next

                    End If
                Next
                TreeViewDetails.ExpandAll()
                TreeViewDetails.Nodes(0).EnsureVisible()
            Else
                MsgBox("Achtung Konfigurationsfehler: Mehrere oder keine Level 0 Entität gefunden!" & "Korrigieren Sie bitte Ihre Eingaben", MsgBoxStyle.Exclamation)
            End If
        Catch ex As Exception
            MsgBox("Error in Load_TreeView:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub
    Private Sub TBPMO_FORM_CONSTRUCTORBindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles TBPMO_FORM_CONSTRUCTORBindingSource.CurrentChanged
        lblSave.Visible = False
        If formloaded = True Then
            Try
                If CONSTRUCTOR_IDTextBox.Text <> "" Then

                    LANGUAGETextBox.Text = USER_LANGUAGE
                    Load_TreeViewEbene()
                    Load_ConstructorUser()
                End If
            Catch ex As Exception
                MsgBox("Error Loading Construct-Data:" & vbNewLine & ex.Message)
            End Try
        End If
    End Sub

    Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeViewDetails.AfterSelect
        Try
            If Not TreeViewDetails.SelectedNode Is Nothing Then
                Dim construct_id As Integer = Integer.Parse(TreeViewDetails.SelectedNode.Tag)
                SELECTED_CONSTRUCTOR_DETAIL_ID = construct_id
                Me.tslblSaveDetail.Visible = False
                Load_Detail(construct_id)
                Select Case XtraTabControl2.SelectedTabPageIndex
                    Case 0
                        Load_QuickDisplay()
                    Case 1

                    Case 2
                        RecordSearch_Config()
                    Case 3
                        Load_TBWH_Users1()
                    Case 4
                        Load_Client_Entity()
                        Load_ClientsforEntity()
                End Select

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

    Private Sub LEVEL1_SELECTCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles LEVEL1_SELECTCheckBox.CheckedChanged
        'Try
        '    If LEVEL1_SELECTCheckBox.Checked Then
        '        SQL_SELECT_EBENE1TextBox.Enabled = True
        '    Else
        '        SQL_SELECT_EBENE1TextBox.Enabled = False
        '    End If
        '    Dim view As String
        '    If SQL_SELECT_EBENE1TextBox.Text <> "" Then
        '        view = SQL_SELECT_EBENE1TextBox.Text.ToUpper.Replace("SELECT * FROM ", "")
        '        view = view.Trim
        '        Dim Sql = "SELECT name FROM sys.columns WHERE object_id = OBJECT_ID('" & view & "')"
        '        If LogErrorsOnly = False Then ClassLogger.Add(" >> " & Sql, False)
        '        Dim DT As DataTable = ClassDatabase.Return_Datatable(Sql)
        '        If DT IsNot Nothing Then
        '            COLUMN_NAME1ComboBox.Items.Clear()
        '            For Each row As DataRow In DT.Rows
        '                COLUMN_NAME1ComboBox.Items.Add(row.Item(0))
        '            Next
        '        End If
        '    End If
        'Catch ex As Exception
        '    MsgBox("Error in LEVEL1_SELECTCheckBox:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        'End Try
    End Sub

    Private Sub tsbtnSave_Click(sender As Object, e As EventArgs) Handles tsbtnSave.Click
        If XtraTabControl2.SelectedTabPageIndex = 1 Then
            Try
                Me.TBPMO_FORM_CONSTRUCTOR_DETAILBindingSource.EndEdit()
                If DD_ECMAdmin.TBPMO_FORM_CONSTRUCTOR_DETAIL.GetChanges Is Nothing = False Then
                    Me.CHANGED_WHOTextBox1.Text = USER_USERNAME
                    Me.TBPMO_FORM_CONSTRUCTOR_DETAILBindingSource.EndEdit()
                    Me.TBPMO_FORM_CONSTRUCTOR_DETAILTableAdapter.Update(DD_ECMAdmin.TBPMO_FORM_CONSTRUCTOR_DETAIL)
                    tslblSaveDetail.Text = "Constructor-Details saved - " & Now
                    Me.tslblSaveDetail.Visible = True
                Else
                    Me.tslblSaveDetail.Visible = False
                End If

            Catch ex As Exception
                MsgBox("Error in Save Constructor-Details:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        End If

        If XtraTabControl2.SelectedTabPageIndex = 2 Then
            Try
                Try
                    lblSaveDocSearch.Visible = False
                    Dim docsearch As Integer
                    If chkWDSearch_Active.Checked Then
                        docsearch = 1
                    Else
                        docsearch = 0
                    End If
                    Dim upd = String.Format("UPDATE TBPMO_FORM_VIEW SET DOCUMENT_VIEW = {0},CHANGED_WHO = '{1}' WHERE FORM_ID = {2} AND SCREEN_ID = {3}", docsearch, USER_USERNAME, SELECTED_ENTITY_ID, CURRENT_SCREEN_ID)
                    ClassDatabase.Execute_non_Query(upd)

                    Dim DOC_SEARCH_TAB1 As Integer
                    If chkDOC_SEARCH_TAB1.Checked Then
                        DOC_SEARCH_TAB1 = 1
                    Else
                        DOC_SEARCH_TAB1 = 0
                    End If
                    Dim ACTIVATE_DOC_SEARCH_ON_EDIT As Integer
                    If chkActivateDSOnEdit.Checked Then
                        ACTIVATE_DOC_SEARCH_ON_EDIT = 1
                    Else
                        ACTIVATE_DOC_SEARCH_ON_EDIT = 0
                    End If
                    Dim sql = String.Format("UPDATE TBPMO_FORM_CONSTRUCTOR_DETAIL SET DOC_SEARCH_TAB1 = {0},ACTIVATE_DOC_SEARCH_ON_EDIT = {1}, CHANGED_WHO = '{2}' where GUID = {3}", DOC_SEARCH_TAB1, ACTIVATE_DOC_SEARCH_ON_EDIT, USER_USERNAME, SELECTED_CONSTRUCTOR_DETAIL_ID)
                    If ClassDatabase.Execute_non_Query(sql) = True Then
                        lblSaveDocSearch.Visible = True
                        lblSaveDocSearch.Text = "Data saved - " & Now
                    End If

                Catch ex As Exception
                    MsgBox("Error in Save DocView-properties 2:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                    lblSaveDocSearch.Visible = False
                End Try
            Catch ex As Exception
                MsgBox("Error in Save DocView-properties 1:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                lblSaveDocSearch.Visible = False
            End Try
        End If

        If XtraTabControl2.SelectedTabPageIndex = 3 And TabControl1.SelectedIndex = 0 Then
            Try
                Me.TBPMO_CONSTRUCTOR_USER_SQLBindingSource.EndEdit()
                If DD_DMSDataSet.TBPMO_CONSTRUCTOR_USER_SQL.GetChanges Is Nothing = False Then
                    Me.CHANGED_WHOTextBox2.Text = USER_USERNAME
                    Me.TBPMO_CONSTRUCTOR_USER_SQLBindingSource.EndEdit()
                    Me.TBPMO_CONSTRUCTOR_USER_SQLTableAdapter.Update(DD_DMSDataSet.TBPMO_CONSTRUCTOR_USER_SQL)
                    lblsaveSQLUser.Visible = True
                Else
                    lblsaveSQLUser.Visible = False
                End If
            Catch ex As Exception
                MsgBox("Error in Save User SQL:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try

        End If
    End Sub


    Private Sub chkWDSearch_Active_CheckedChanged(sender As Object, e As EventArgs) Handles chkWDSearch_Active.CheckedChanged
        Try
            If chkWDSearch_Active.Checked Then
                XtraTabControlSV.Enabled = True
                Load_TBAD_Users()
                Load_Supervisor()
                Load_Supervisor_Controls_Choose()
                Load_Supervisor_Controls()
                chkDOC_SEARCH_TAB1.Enabled = True
            Else
                XtraTabControlSV.Enabled = False
                chkDOC_SEARCH_TAB1.Enabled = False
            End If
        Catch ex As Exception
            MsgBox("Error in Checked Change WD-Search:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub XtraTabControl2_SelectedPageChanged(sender As Object, e As DevExpress.XtraTab.TabPageChangedEventArgs) Handles XtraTabControl2.SelectedPageChanged
        Select Case XtraTabControl2.SelectedTabPageIndex
            Case 0
                Load_QuickDisplay()
            Case 2
                RecordSearch_Config()
            Case 3
                Load_TBWH_Users1()
            Case 4
                Load_Client_Entity()
                Load_ClientsforEntity()
        End Select
    End Sub
    Public Class MyListBoxItem
        Private _text As String
        Private _extraData As String

        Public Property Text As String
            Get
                Return _text
            End Get
            Set(ByVal value As String)
                _text = value
            End Set
        End Property

        Public Property ExtraData As String
            Get
                Return _extraData
            End Get
            Set(ByVal value As String)
                _extraData = value
            End Set
        End Property

        Public Overrides Function ToString() As String
            Return Text
        End Function

    End Class
    Public Sub Load_Client_Entity()
        Try
            Dim sql = String.Format("SELECT GUID, CLIENT_NAME FROM TBDD_CLIENT WHERE GUID IN (SELECT CLIENT_ID FROM TBDD_CLIENT_USER WHERE USER_ID = {0})", USER_GUID)
            Dim DT1 As DataTable = ClassDatabase.Return_Datatable(sql)
            chklbxClient.Items.Clear()
            For Each row As DataRow In DT1.Rows
                chklbxClient.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
            Next
           
        Catch ex As Exception
            MsgBox("UnexpectedError Load_Client_Entity:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Sub Load_ClientsforEntity()
        Try
            Dim sql = String.Format("SELECT T.GUID, T1.CLIENT_NAME FROM TBPMO_CLIENT_ENTITY T, TBDD_CLIENT T1 WHERE T.CLIENT_ID = T1.GUID " & _
                        "AND T1.GUID IN (SELECT CLIENT_ID FROM TBDD_CLIENT_USER WHERE USER_ID = {0}) AND T.ENTITY_ID = {1}", USER_GUID, SELECTED_ENTITY_ID)


            Dim DT As DataTable = ClassDatabase.Return_Datatable(Sql)
            chklbxEntitiesforClient.Items.Clear()
            For Each row1 As DataRow In DT.Rows
                chklbxEntitiesforClient.Items.Add(New MyListBoxItem() With {.Text = row1.Item(1), .ExtraData = row1.Item(0)})
            Next
        Catch ex As Exception
            MsgBox("UnexpectedError Load_ClientsforEntity:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Public Sub Load_TBWH_Users1()
        Try
            Dim sql = String.Format("SELECT T.* FROM TBDD_USER T WHERE T.MODULE_RECORD_ORG = 1 AND T.GUID IN (SELECT USER_ID FROM TBPMO_CONSTRUCTOR_USER WHERE CONSTRUCT_ID = {0}) ORDER BY T.USERNAME", CONSTRUCTOR_IDTextBox.Text)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            DD_ECMAdmin.TBWH_Users1.Clear()
            For Each row As DataRow In DT.Rows
                Dim newUserRow As DD_ECMAdmin.TBWH_Users1Row
                newUserRow = DD_ECMAdmin.TBWH_Users1.NewTBWH_Users1Row
                newUserRow.Username = row.Item("USERNAME")
                newUserRow.Surname = row.Item("NAME")
                newUserRow.Prename = row.Item("PRENAME")
                Try
                    newUserRow.Email = row.Item("EMAIL")
                Catch ex As Exception
                    newUserRow.Email = ""
                End Try

                newUserRow.ID = row.Item("GUID")
                DD_ECMAdmin.TBWH_Users1.Rows.Add(newUserRow)
                ' chklbxUsersforClient.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
            Next
        Catch ex As Exception
            MsgBox("UnexpectedError Load_UserSQL:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Public Sub Load_TBAD_Users()
        Try
            Dim sql = String.Format("SELECT T.* FROM TBDD_USER T WHERE T.MODULE_RECORD_ORG = 1 AND T.GUID IN (SELECT USER_ID FROM TBPMO_CONSTRUCTOR_USER WHERE CONSTRUCT_ID = {0}) ORDER BY T.USERNAME", CONSTRUCTOR_IDTextBox.Text)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            DD_ECMAdmin.TBAD_Users.Clear()
            For Each row As DataRow In DT.Rows
                Dim newUserRow As DD_ECMAdmin.TBAD_UsersRow
                newUserRow = DD_ECMAdmin.TBAD_Users.NewTBAD_UsersRow
                newUserRow.Username = row.Item("USERNAME")
                newUserRow.Surname = row.Item("NAME")
                newUserRow.Prename = row.Item("PRENAME")
                Try
                    newUserRow.Email = row.Item("EMAIL")
                Catch ex As Exception
                    newUserRow.Email = ""
                End Try

                newUserRow.ID = row.Item("GUID")
                DD_ECMAdmin.TBAD_Users.Rows.Add(newUserRow)
                ' chklbxUsersforClient.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
            Next
        Catch ex As Exception
            MsgBox("UnexpectedError Load_TBAD_Users:" & vbNewLine & ex.Message)
        End Try
    End Sub

    Public Sub Load_Supervisor()
        Try
            Dim sql = String.Format("SELECT T.* FROM TBDD_USER T WHERE T.MODULE_RECORD_ORG = 1 AND T.GUID IN (SELECT USER_ID FROM TBPMO_ENTITY_SUPERVISOR WHERE ENTITY_ID = {0}) ORDER BY T.USERNAME", SELECTED_ENTITY_ID)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            DD_ECMAdmin.TBWH_Users2.Clear()
            For Each row As DataRow In DT.Rows
                Dim newUserRow As DD_ECMAdmin.TBWH_Users2Row
                newUserRow = DD_ECMAdmin.TBWH_Users2.NewTBWH_Users2Row
                newUserRow.Username = row.Item("USERNAME")
                newUserRow.Surname = row.Item("NAME")
                newUserRow.Prename = row.Item("PRENAME")
                Try
                    newUserRow.Email = row.Item("EMAIL")
                Catch ex As Exception
                    newUserRow.Email = ""
                End Try

                newUserRow.ID = row.Item("GUID")
                DD_ECMAdmin.TBWH_Users2.Rows.Add(newUserRow)
                ' chklbxUsersforClient.Items.Add(New MyListBoxItem() With {.Text = row.Item(1), .ExtraData = row.Item(0)})
            Next
        Catch ex As Exception
            MsgBox("UnexpectedError Load_Supervisor:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Public Sub Load_Supervisor_Controls_Choose()
        Try
            Dim sql = String.Format("select GUID, NAME + '/' + COL_NAME as control from tbpmo_Control where FORM_ID = {0} and CONTROL_TYPE_ID IN (2,3,12) ORDER BY NAME", SELECTED_ENTITY_ID)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            cmbSupervisorControls.DataSource = DT
            cmbSupervisorControls.DisplayMember = DT.Columns(1).ColumnName
            cmbSupervisorControls.ValueMember = DT.Columns(0).ColumnName
        Catch ex As Exception
            MsgBox("UnexpectedError Load_Supervisor_Controls_Choose:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Public Sub Load_Supervisor_Controls()
        Try
            Dim sql = String.Format("select T1.GUID, T.NAME + '/' + T.COL_NAME as [control] from tbpmo_Control T, TBPMO_SUPERVISOR_CONTROLS T1 " & _
                        "where T.GUID = T1.CONTROL_ID AND T.FORM_ID = {0} ORDER BY T.NAME", SELECTED_ENTITY_ID)
            Dim DT As DataTable = ClassDatabase.Return_Datatable(sql)
            CheckedListBoxSupervisorControls.Items.Clear()
            For Each row1 As DataRow In DT.Rows
                CheckedListBoxSupervisorControls.Items.Add(New MyListBoxItem() With {.Text = row1.Item(1), .ExtraData = row1.Item(0)})
            Next
        Catch ex As Exception
            MsgBox("UnexpectedError Load_Supervisor_Controls:" & vbNewLine & ex.Message)
        End Try
    End Sub
    Private Sub btnAddControl_Click(sender As Object, e As EventArgs) Handles btnAddControl.Click
        Try
            Dim i = listBoxControls.SelectedValue
            If Not IsNothing(i) Then
                Dim insert = "INSERT INTO TBPMO_FORM_CONSTR_QUICK_DISPLAY (CONSTRUCT_ID, CONTROL_ID,ADDED_WHO) VALUES (" & SELECTED_CONSTRUCTOR_DETAIL_ID & ", " & i & ",'" & USER_USERNAME & "')"
                If ClassDatabase.Execute_non_Query(insert) Then
                    Load_QuickDisplay()
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in Adding Control to Quick-Display: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btndeleteControl_Click(sender As Object, e As EventArgs) Handles btndeleteControl.Click
        Try
            Dim i = ListBoxConfiguredDisplay.SelectedValue
            If Not IsNothing(i) Then
                Dim delete = "DELETE FROM TBPMO_FORM_CONSTR_QUICK_DISPLAY  WHERE GUID = " & i
                If ClassDatabase.Execute_non_Query(delete) Then
                    Load_QuickDisplay()
                End If
            End If
        Catch ex As Exception
            MsgBox("Error in Deleting Control from Quick-Display: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub ListBoxConfiguredDisplay_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBoxConfiguredDisplay.SelectedIndexChanged
        lblChangeHeadline.Visible = False
        If ListBoxConfiguredDisplay.SelectedIndex <> -1 Then
            Try
                Dim txt As String = ListBoxConfiguredDisplay.Text
                Me.btnSetHeadline.Text = "Set '" & txt & "'" & vbNewLine & "as Headline"
                Me.btnSetHeadline.Visible = True
            Catch ex As Exception

            End Try

        End If
    End Sub

    Private Sub btnSetHeadline_Click(sender As Object, e As EventArgs) Handles btnSetHeadline.Click
        Dim upd = "UPDATE TBPMO_FORM_CONSTR_QUICK_DISPLAY SET HEADLINE = 1, CHANGED_WHO = '" & USER_USERNAME & "' WHERE GUID = " & ListBoxConfiguredDisplay.SelectedValue
        If ClassDatabase.Execute_non_Query(upd) Then
            lblChangeHeadline.Visible = True
        End If
    End Sub

    Private Sub btnSetQuickViewPicture_Click(sender As Object, e As EventArgs) Handles btnSetQuickViewPicture.Click
        Dim DEL As String = "DELETE FROM TBPMO_FORM_CONSTR_QUICK_DISPLAY WHERE CONSTRUCT_ID = " & SELECTED_CONSTRUCTOR_DETAIL_ID & " AND CONTROL_ID in (SELECT GUID FROM TBPMO_CONTROL WHERE CONTROL_TYPE_ID = 6)"
        If ClassDatabase.Execute_non_Query(DEL) Then
            Try
                Dim i = listBoxControls.SelectedValue
                If Not IsNothing(i) Then
                    Dim insert = "INSERT INTO TBPMO_FORM_CONSTR_QUICK_DISPLAY (CONSTRUCT_ID, CONTROL_ID,PICTURE,ADDED_WHO) VALUES (" & SELECTED_CONSTRUCTOR_DETAIL_ID & ", " & i & ",1,'" & USER_USERNAME & "')"
                    If ClassDatabase.Execute_non_Query(insert) Then
                        Load_QuickDisplay()
                        lblQuickViewAdded.Visible = True
                    Else
                        lblQuickViewAdded.Visible = False
                    End If
                End If
            Catch ex As Exception
                MsgBox("Error in Adding Control to Quick-Display: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                lblQuickViewAdded.Visible = False
            End Try
        End If
    End Sub

    Private Sub listBoxControls_SelectedIndexChanged(sender As Object, e As EventArgs) Handles listBoxControls.SelectedIndexChanged
        If listBoxControls.SelectedIndex <> -1 Then
            Try
                Dim i = listBoxControls.SelectedValue
                If i.ToString.Contains("DataRowV") Then Exit Sub
                If Not IsNothing(i) Then
                    Dim count = ClassDatabase.Execute_Scalar("SELECT COUNT(T1.GUID) FROM TBPMO_CONTROL T1 WHERE T1.CONTROL_TYPE_ID = 6 and T1.GUID = " & i)
                    If count = 1 Then
                        Me.btnSetQuickViewPicture.Visible = True
                    Else
                        Me.btnSetQuickViewPicture.Visible = False
                    End If
                End If
                lblQuickViewAdded.Visible = False
            Catch ex As Exception
                MsgBox("Error in CHECK CONTROL IS PICTURE: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                Me.btnSetQuickViewPicture.Visible = False
            End Try
        End If
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim DEL As String = "DELETE FROM TBPMO_FORM_CONSTR_QUICK_DISPLAY WHERE CONSTRUCT_ID = " & SELECTED_CONSTRUCTOR_DETAIL_ID & " AND CONTROL_ID in (SELECT GUID FROM TBPMO_CONTROL WHERE CONTROL_TYPE_ID = 6)"
        If ClassDatabase.Execute_non_Query(DEL) Then
            Load_QuickDisplay()
        End If
    End Sub
    Private Function CreateTable(ByVal rowCount As Integer) As DataTable
        Dim tbl As New DataTable()
        tbl.Columns.Add("Name", GetType(String))
        tbl.Columns.Add("ID", GetType(Integer))
        tbl.Columns.Add("Image", GetType(Image))
        tbl.Columns.Add("Date", GetType(Date))
        For i As Integer = 0 To rowCount - 1
            tbl.Rows.Add(New Object() {String.Format("Name{0}", i), i, ImageCollection1.Images(i Mod 4), Date.Now.AddDays(i - 3)})
        Next i
        Return tbl
    End Function

    Private Sub LOAD_DIRECTCheckBox_CheckedChanged(sender As Object, e As EventArgs) Handles LOAD_DIRECTCheckBox.CheckedChanged

    End Sub

    Private Sub btnAddUser2ConstructorREL_Click(sender As Object, e As EventArgs) Handles btnAddUser2ConstructorREL.Click
        Try
            For Each row As DataRow In DD_ECMAdmin.TBAD_Users.Rows
                If row.Item(0) = CBool(True) Then
                    Dim home As Integer
                    If CheckBoxHome.Checked Then
                        home = 1
                    Else
                        home = 0
                    End If
                    Dim insert = "INSERT INTO TBPMO_CONSTRUCTOR_USER (CONSTRUCT_ID, USER_ID,ADDED_WHO,HOME_MENUE) VALUES (" & CONSTRUCTOR_IDTextBox.Text & ", " & row.Item(5) & ",'" & USER_USERNAME & "'," & home & ")"
                    If ClassDatabase.Execute_non_Query(insert) = False Then
                        MsgBox("Could not insert the User-Definition....Check the logfile!", MsgBoxStyle.Exclamation)
                    End If
                End If
            Next
            For Each row As DataRow In DD_ECMAdmin.TBAD_Users.Rows
                row.Item(0) = CBool(False)
            Next
            Load_ConstructorUser()
        Catch ex As Exception
            MsgBox("Error while adding user to Constructor-Relation: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btndeleteUserConstructorRel_Click(sender As Object, e As EventArgs) Handles btndeleteUserConstructorRel.Click
        Try
            Dim refresh As Boolean = False
            For Each row As DataRow In DD_ECMAdmin.TBWH_Users1.Rows
                If row.Item(0) = CBool(True) Then
                    Dim delete = "DELETE FROM TBPMO_CONSTRUCTOR_USER  WHERE GUID = " & row.Item(5)
                    If ClassDatabase.Execute_non_Query(delete) Then
                        refresh = True
                    End If
                End If
            Next
            If refresh = True Then Load_ConstructorUser()
        Catch ex As Exception
            MsgBox("Error while deleting user to Constructor-Relation: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub FormDesignerToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles FormDesignerToolStripMenuItem.Click
        Try
            Dim SelectedNode As TreeNode = TryCast(TreeViewDetails.SelectedNode, TreeNode)
            If SelectedNode IsNot Nothing Then
                Dim sql = String.Format("SELECT FORM_ID FROM TBPMO_FORM_CONSTRUCTOR_DETAIL WHERE GUID = {0}", SelectedNode.Tag)
                Dim FormId As Integer = ClassDatabase.Execute_Scalar(sql)
                If FormId > 0 Then
                    CURRENT_ENTITY_ID = FormId
                    OpenFormLevelDesigner()
                End If
            End If
        Catch ex As Exception
            MsgBox("Unexpected Error in Open Designer: " & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnChangeHOMESTANDARD_Click(sender As Object, e As EventArgs) Handles btnChangeHOMESTANDARD.Click
        Try
            Dim refresh As Boolean = False
            For Each row As DataRow In DD_ECMAdmin.TBWH_Users1.Rows
                If row.Item(0) = CBool(True) Then
                    Dim sql = "SELECT HOME_MENUE FROM TBPMO_CONSTRUCTOR_USER  WHERE GUID = " & row.Item(5)
                    Dim Home = ClassDatabase.Execute_Scalar(sql)
                    If Home = True Then
                        Home = 0
                    Else
                        Home = 1
                    End If
                    sql = "UPDATE TBPMO_CONSTRUCTOR_USER SET HOME_MENUE = " & Home & " WHERE GUID = " & row.Item(5)
                    If ClassDatabase.Execute_non_Query(sql) Then
                        refresh = True
                    End If
                End If
            Next
            If refresh = True Then Load_ConstructorUser()
        Catch ex As Exception
            MsgBox("Error while deleting user to Constructor-Relation: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Sub btnAddUserSQL_Click(sender As Object, e As EventArgs) Handles btnAddUserSQL.Click
        If GUIDTextBox.Text = "" Then
            TBPMO_CONSTRUCTOR_USER_SQLBindingSource.AddNew()
            SQL_COMMANDTextBox.Enabled = True
            SQL_COMMANDTextBox.BackColor = Color.PapayaWhip
            SQL_COMMANDTextBox.Focus()
        End If
    End Sub

    Private Sub TBPMO_CONSTRUCTOR_USER_SQLBindingSource_AddingNew(sender As Object, e As System.ComponentModel.AddingNewEventArgs) Handles TBPMO_CONSTRUCTOR_USER_SQLBindingSource.AddingNew
        Try
            Dim USERID = GridViewUserSQL.GetFocusedRowCellValue(GridViewUserSQL.Columns("ID"))
            If Not USERID Is Nothing Then
                DD_DMSDataSet.TBPMO_CONSTRUCTOR_USER_SQL.ADDED_WHOColumn.DefaultValue = USER_USERNAME
                DD_DMSDataSet.TBPMO_CONSTRUCTOR_USER_SQL.CONSTR_DET_IDColumn.DefaultValue = SELECTED_CONSTRUCTOR_DETAIL_ID
                DD_DMSDataSet.TBPMO_CONSTRUCTOR_USER_SQL.USER_IDColumn.DefaultValue = USERID
            End If
           
        Catch ex As Exception
            MsgBox("Error while Adding User-Restrictions:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try

    End Sub

    Private Sub SQL_COMMANDTextBox_TextChanged(sender As Object, e As EventArgs) Handles SQL_COMMANDTextBox.TextChanged
        If SQL_COMMANDTextBox.Text.Trim().Count = 0 Then
            dgvPlaceholders.Enabled = False
            SQL_COMMANDTextBox.BackColor = Color.LightGray
        Else
            dgvPlaceholders.Enabled = True
            SQL_COMMANDTextBox.BackColor = Color.PapayaWhip
        End If

        CheckForPlaceholders()
    End Sub

    Private Sub CheckForPlaceholders()
        Dim count As Integer = 0
        Dim text As String = Me.SQL_COMMANDTextBox.Text
        Dim atPlaceholderRegex = New Regex(AtPlaceholderPattern, RegexOptions.IgnoreCase)
        Dim matches As MatchCollection = atPlaceholderRegex.Matches(text)

        dgvPlaceholders.Rows.Clear()
        Dim USERID = GridViewUserSQL.GetFocusedRowCellValue(GridViewUserSQL.Columns("ID"))
        For Each match As Match In matches
            Dim placeholder = ""
            Select Case match.Value.ToUpper
                Case "@USER_ID"
                    placeholder = USERID
            End Select
            dgvPlaceholders.Rows.Add({match.Value, placeholder})
        Next
    End Sub

    Private Sub btnTestSQL_Click(sender As Object, e As EventArgs) Handles btnTestSQL.Click
        Try
            Dim EntSQL = "SELECT T.* FROM VWTEMP_PMO_FORM" & SELECTED_ENTITY_ID.ToString & " T"
            Dim query As String = EntSQL & " " & SQL_COMMANDTextBox.Text

            For Each row As DataGridViewRow In dgvPlaceholders.Rows
                Dim placeholder As String = row.Cells(0).Value
                Dim replacement As String = row.Cells(1).Value

                ' Wenn Ersetzung ausgefüllt wurde, Platzhalter damit ersetzen
                If Not String.IsNullOrEmpty(replacement) Then
                    query = query.Replace(placeholder, replacement)
                Else
                    MsgBox("Please add a test-value for the placeholder '" & placeholder & "'!", MsgBoxStyle.Exclamation, "Missing value:")
                    Exit Sub
                End If
            Next
            Dim DT As DataTable = ClassDatabase.Return_Datatable(query)

            If DT IsNot Nothing Then
                dgvResult.DataSource = DT
            End If
        Catch ex As Exception
            MsgBox("Error in Testing User-Restriction SQL:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try


    End Sub

    Private Sub btnsaddUser2Client_Click(sender As Object, e As EventArgs) Handles btnsaddUser2Client.Click

        For Each obj As Object In chklbxClient.CheckedItems
            Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
            Dim sql = "select count(*) from TBPMO_CLIENT_ENTITY Where CLIENT_ID = " & item.ExtraData & " AND ENTITY_ID = " & SELECTED_ENTITY_ID
            If ClassDatabase.Execute_Scalar(sql) = 0 Then
                sql = String.Format("INSERT INTO TBPMO_CLIENT_ENTITY (CLIENT_ID, ENTITY_ID, ADDED_WHO) VALUES ({0}, {1}, '{2}')", item.ExtraData, SELECTED_ENTITY_ID, USER_USERNAME)
                If ClassDatabase.Execute_non_Query(sql) = False Then
                    MsgBox("Error in Adding Entity to Client!", MsgBoxStyle.Critical)
                End If
            End If
        Next
        Load_ClientsforEntity()
    End Sub

    Private Sub btndeleteEntityfromClient_Click(sender As Object, e As EventArgs) Handles btndeleteEntityfromClient.Click
        For Each obj As Object In chklbxEntitiesforClient.CheckedItems
            Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
            Dim sql
            sql = String.Format("DELETE FROM TBPMO_CLIENT_ENTITY  WHERE GUID = {0}", item.ExtraData)
            If ClassDatabase.Execute_non_Query(sql) = False Then
                MsgBox(String.Format("Error in deleting Entity from Client", item.Text), MsgBoxStyle.Critical)
            End If
        Next
        Load_ClientsforEntity()
    End Sub

    Private Sub TBWH_Users1BindingSource_CurrentChanged(sender As Object, e As EventArgs) Handles TBWH_Users1BindingSource.CurrentChanged
        Load_SQL_ForUSer()
    End Sub
    Sub Load_SQL_ForUSer()
        Try
            Try
                Dim USERID = GridViewUserSQL.GetFocusedRowCellValue(GridViewUserSQL.Columns("ID"))
                If Not USERID Is Nothing Then
                    Me.TBPMO_CONSTRUCTOR_USER_SQLTableAdapter.Connection.ConnectionString = MyConnectionString
                    Me.TBPMO_CONSTRUCTOR_USER_SQLTableAdapter.Fill(Me.DD_DMSDataSet.TBPMO_CONSTRUCTOR_USER_SQL, SELECTED_CONSTRUCTOR_DETAIL_ID, USERID)
                    If SQL_COMMANDTextBox.Text <> "" Or ADDED_WHOTextBox2.Text <> "" Then
                        SQL_COMMANDTextBox.Enabled = True
                    Else
                        SQL_COMMANDTextBox.Enabled = False
                    End If

                End If

            Catch ex As System.Exception
                If Not ex.Message.ToLower.Contains("atarowview") Then
                    MsgBox("Error while loading User-Restrictions:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
                End If
            End Try
            lblsaveSQLUser.Visible = False
        Catch ex As Exception
            MsgBox("Error in Load SQL for User:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub BindingNavigatorDeleteItem_Click(sender As Object, e As EventArgs) Handles BindingNavigatorDeleteItem.Click
        Dim msg As String = "Wollen Sie diesen Constructor wirklich löschen?"
        If USER_LANGUAGE <> "de-DE" Then
            msg = "Do You really want to delete this constructor?"
        End If
        Dim result As MsgBoxResult = MsgBox(msg, MsgBoxStyle.YesNo)
        If result = MsgBoxResult.Yes Then
            Try
                Dim CurrentID = CONSTRUCTOR_IDTextBox.Text
                Dim sql = "EXEC PRPMO_DELETE_CONSTRUCTOR " & CurrentID
                If ClassDatabase.Execute_non_Query(sql) = True Then
                    MsgBox("Constructor was deleted!", MsgBoxStyle.Information)
                    Load_Head()
                    Load_TreeViewEbene()
                    Load_ConstructorUser()
                End If
            Catch ex As Exception
                MsgBox("Unexpected Error in delete Constructor:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
            End Try
        Else
            MsgBox("Unexpected error in executing delete-statement! Check log!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub btnAddUser2Supervisor_Click(sender As Object, e As EventArgs) Handles btnAddUser2Supervisor.Click
        Try
            If cmbRight.Text = "" Then
                MsgBox("Please choose a right!", MsgBoxStyle.Exclamation)
                cmbRight.DroppedDown = True
                Exit Sub
            End If
            For Each row As DataRow In DD_ECMAdmin.TBAD_Users.Rows
                If row.Item(0) = CBool(True) Then
                    Dim right As String
                    Select Case cmbRight.Text
                        Case "Admin"
                            right = "4"
                        Case "Read/Write"
                            right = "3"
                    End Select

                    Dim sel = String.Format("SELECT COUNT(GUID) FROM TBPMO_ENTITY_SUPERVISOR WHERE ENTITY_ID = {0} AND USER_ID = {1}", SELECTED_ENTITY_ID, row.Item(5))
                    If ClassDatabase.Execute_Scalar(sel) = 0 Then
                        Dim insert = String.Format("INSERT INTO TBPMO_ENTITY_SUPERVISOR ([ENTITY_ID], USER_ID,RIGHT1,ADDED_WHO) VALUES ({0},{1},'{2}','{3}')", SELECTED_ENTITY_ID, row.Item(5), right, USER_USERNAME)
                        If ClassDatabase.Execute_non_Query(insert) Then
                        End If
                    End If
                End If
            Next
            For Each row As DataRow In DD_ECMAdmin.TBAD_Users.Rows
                row.Item(0) = CBool(False)
            Next
            Load_Supervisor()
        Catch ex As Exception
            MsgBox("Error while adding user to Constructor-Relation: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnDeleteUserSupervisor_Click(sender As Object, e As EventArgs) Handles btnDeleteUserSupervisor.Click
        Try
            Dim refresh As Boolean = False
            For Each row As DataRow In DD_ECMAdmin.TBWH_Users2.Rows
                If row.Item(0) = CBool(True) Then
                    Dim delete = String.Format("DELETE FROM TBPMO_ENTITY_SUPERVISOR WHERE USER_ID = {0} AND ENTITY_ID = {1}", row.Item(5), SELECTED_ENTITY_ID)
                    If ClassDatabase.Execute_non_Query(delete) Then
                        refresh = True
                    End If
                End If
            Next
            If refresh = True Then Load_Supervisor()
        Catch ex As Exception
            MsgBox("Error while deleting user to Constructor-Relation: " & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    Private Sub btnAddSupervisorControl_Click(sender As Object, e As EventArgs) Handles btnAddSupervisorControl.Click
        If cmbSupervisorControls.SelectedIndex <> -1 Then
            Dim sql = "select count(*) from TBPMO_SUPERVISOR_CONTROLS Where CONTROL_ID = " & cmbSupervisorControls.SelectedValue
            If ClassDatabase.Execute_Scalar(sql) = 0 Then
                sql = String.Format("INSERT INTO TBPMO_SUPERVISOR_CONTROLS (CONTROL_ID, ADDED_WHO) VALUES ({0},'{1}')", cmbSupervisorControls.SelectedValue, USER_USERNAME)
                If ClassDatabase.Execute_non_Query(sql) = False Then
                    MsgBox("Error in Adding Supervisor-Control! Check log", MsgBoxStyle.Critical)
                Else
                    Load_Supervisor_Controls()
                End If
            End If
        End If
    End Sub

    Private Sub btndeleteSupervisorControl_Click(sender As Object, e As EventArgs) Handles btndeleteSupervisorControl.Click
        For Each obj As Object In CheckedListBoxSupervisorControls.CheckedItems
            Dim item As MyListBoxItem = CType(obj, MyListBoxItem)
            Dim sql
            sql = String.Format("DELETE FROM TBPMO_SUPERVISOR_CONTROLS  WHERE GUID = {0}", item.ExtraData)
            If ClassDatabase.Execute_non_Query(sql) = False Then
                MsgBox(String.Format("Error in deleting SupervisorControl", item.Text), MsgBoxStyle.Critical)
            End If
        Next
        Load_Supervisor_Controls()
    End Sub
End Class