Imports System.Windows.Forms

Public Class ClassControlBuilder
    Private _master_panel As Panel
    Private _current_control As Control
    Private _begin_location As Point
    Private _end_location As Point
    Private _mouse_down_handler As MouseEventHandler
    Private _mouse_up_handler As MouseEventHandler
    Private _mouse_move_handler As MouseEventHandler
    Private _mouse_click_handler As EventHandler
    Private _group_box_drag_drop_handler As DragEventHandler
    Private _tool_tip_handler As EventHandler
    Private _onRecordChangedName As String = "OnRecordChanged"
    Private _onMouseHoverName As String = "OnMouseHover"
    Private _events As System.ComponentModel.EventHandlerList = Nothing

    Protected ReadOnly Property Events() As System.ComponentModel.EventHandlerList
        Get
            If _events Is Nothing Then
                _events = New System.ComponentModel.EventHandlerList
            End If
            Return _events
        End Get
    End Property

    ' +++ RecordChanged Event +++
    Public Custom Event OnRecordChanged As EventHandler
        AddHandler(value As EventHandler)
            Me.Events.AddHandler(_onRecordChangedName, value)
        End AddHandler

        RemoveHandler(value As EventHandler)
            Me.Events.RemoveHandler(_onRecordChangedName, value)
        End RemoveHandler

        RaiseEvent(sender As Object, e As EventArgs)
            CType(Me.Events(_onRecordChangedName), EventHandler).Invoke(sender, e)
        End RaiseEvent
    End Event

    Public Custom Event OnMouseHover As EventHandler
        AddHandler(value As EventHandler)
            Me.Events.AddHandler(_onMouseHoverName, value)
        End AddHandler

        RemoveHandler(value As EventHandler)
            Me.Events.RemoveHandler(_onMouseHoverName, value)
        End RemoveHandler

        RaiseEvent(sender As Object, e As EventArgs)
            CType(Me.Events(_onMouseHoverName), EventHandler).Invoke(sender, e)
        End RaiseEvent
    End Event

    ' ==================================================================================
    ' Handler für alle Controls
    ' ==================================================================================
    Public Sub RecordChanged(sender As Object, ByVal e As EventArgs)
        Dim onRecordChangedHandler As EventHandler = CType(Me.Events(_onRecordChangedName), EventHandler)

        If (onRecordChangedHandler IsNot Nothing) Then
            Console.WriteLine("RecordChanged")
            onRecordChangedHandler.Invoke(sender, e)
        End If
    End Sub

    ' CheckedListBox hat andere Handler Signatur
    Public Sub RecordChanged(sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ItemCheckEventArgs)
        Dim onRecordChangedHandler As EventHandler = CType(Me.Events(_onRecordChangedName), EventHandler)

        If (onRecordChangedHandler IsNot Nothing) Then
            onRecordChangedHandler.Invoke(sender, e)
        End If
    End Sub

    Public Sub MouseHover(sender As Object, e As EventArgs)
        Dim onMouseHoverHandler As EventHandler = CType(Me.Events(_onMouseHoverName), EventHandler)

        If onMouseHoverHandler IsNot Nothing Then
            onMouseHoverHandler.Invoke(sender, e)
        End If
    End Sub

    Public Sub OnTextBoxFocus(sender As Object, ByVal e As EventArgs)
        Dim box As TextBox = sender
        box.BackColor = Color.LemonChiffon

        box.SelectAll()
    End Sub
    Public Sub OnTextBoxLostFocus(sender As Object, ByVal e As EventArgs)
        Dim box As TextBox = sender
        box.BackColor = Color.White
    End Sub
    Public Sub OnTextBoxTextChanged(sender As Object, ByVal e As EventArgs)

    End Sub
    Public Sub OnComboBoxFocus(sender As Object, ByVal e As EventArgs)
        Dim combo As ComboBox = sender
        combo.BackColor = Color.LemonChiffon
    End Sub
    Public Sub OnComboBoxLostFocus(sender As Object, ByVal e As EventArgs)
        Dim combo As ComboBox = sender
        combo.BackColor = Color.White
    End Sub

    Public Sub OnComboBoxValueChanged(sender As Object, ByVal e As EventArgs)
        Try
            Dim control As Control = DirectCast(sender, Control)
            Dim controlId As Integer = DirectCast(control.Tag, ClassControlMetadata).Id
            Dim SQL As String = String.Format("SELECT GUID, SQL_COMMAND_1 FROM TBPMO_CONTROL WHERE SQL_COMMAND_1 LIKE '%@{0}@%'", controlId)
            Dim value

            Select Case control.GetType()
                Case GetType(ComboBox)
                    value = DirectCast(control, ComboBox).SelectedValue
                Case Else
                    Exit Sub
            End Select

            If String.IsNullOrEmpty(value) Then
                Exit Sub
            End If

            Dim datatable As DataTable = ClassDatabase.Return_Datatable(SQL)

            If datatable.Rows.Count = 0 Then
                Exit Sub
            End If

            For Each row As DataRow In datatable.Rows
                Dim sqlcommand As String = row.Item("SQL_COMMAND_1")

                If IsNothing(sqlcommand) Then
                    Continue For
                End If

                Dim regex As New System.Text.RegularExpressions.Regex("(@(\d+)@)")
                Dim match As System.Text.RegularExpressions.Match = regex.Match(sqlcommand)

                If match.Success Then
                    ' DependingControlId bezeichnet das Control, das die Abhängigkeit enthält
                    Dim dependingControlId As Integer = row.Item("GUID")
                    Dim panel As Panel = DirectCast(control.Parent, Panel)
                    ' Über die Id das Control finden
                    Dim dependingControl As Control = panel.Controls.OfType(Of Control)().Where(Function(c As Control)
                                                                                                    Return DirectCast(c.Tag, ClassControlMetadata).Id = dependingControlId
                                                                                                End Function).SingleOrDefault()

                    sqlcommand = sqlcommand.Replace(match.Groups(1).Value, value)
                    Console.WriteLine("Executing SQL_COMMAND: {0} for controlID {1}", sqlcommand, dependingControlId)
                    Dim dt As DataTable = ClassDatabase.Return_Datatable(sqlcommand)

                    Select Case control.GetType()
                        Case GetType(ComboBox)
                            ControlLoader.Combobox.SetDataSource(DirectCast(dependingControl, ComboBox), dt)
                    End Select


                End If
            Next

            'Dim sqlcommand As String = datatable.Rows(0).Item("SQL_COMMAND_1")

            'If IsNothing(sqlcommand) Then
            '    Exit Sub
            'End If

            'If String.IsNullOrEmpty(value) Then
            '    Exit Sub
            'End If



            'Dim regex As New System.Text.RegularExpressions.Regex("(@(\d+)@)")
            'Dim match As System.Text.RegularExpressions.Match = regex.Match(sqlcommand)

            'If match.Success Then
            '    ' DependingControlId bezeichnet das Control, das die Abhängigkeit enthält
            '    Dim dependingControlId As Integer = datatable.Rows(0).Item("GUID")
            '    Dim panel As Panel = DirectCast(control.Parent, Panel)
            '    ' Über die Id das Control finden
            '    Dim dependingControl As ComboBox = panel.Controls.OfType(Of ComboBox)().Where(Function(c As ComboBox)
            '                                                                                      Return DirectCast(c.Tag, ClassControlMetadata).Id = dependingControlId
            '                                                                                  End Function).SingleOrDefault()

            '    sqlcommand = sqlcommand.Replace(match.Groups(1).Value, value)
            '    Console.WriteLine("Executing SQL_COMMAND: {0}", sqlcommand)
            '    Dim dt As DataTable = ClassDatabase.Return_Datatable(sqlcommand)
            '    ControlLoader.Combobox.SetDataSource(dependingControl, dt)
            'End If

            Console.WriteLine("value changed")
        Catch ex As Exception
            MsgBox("Error in OnComboBoxValueChanged: " & ex.Message)
        End Try
    End Sub

    ' ==================================================================================
    ' Mouse Up/Down/Move-Handler für LevelDesigner festlegen
    ' RecordChanged-Handler für Constructor festlegen
    ' ==================================================================================
    Private Sub SetEventHandlers(control As Control)
        If Not IsNothing(_mouse_down_handler) Then
            AddHandler control.MouseDown, Me._mouse_down_handler
            AddHandler control.MouseUp, Me._mouse_up_handler
            AddHandler control.MouseMove, Me._mouse_move_handler
            AddHandler control.Click, Me._mouse_click_handler
        End If

        Dim type As String = control.GetType().Name
        Dim eventArgs As New System.EventArgs

        ' Hover Handler gilt für alle Controls
        AddHandler control.MouseHover, AddressOf MouseHover

        Select Case type
            Case "TextBox"
                Dim textbox As TextBox = CType(control, TextBox)
                AddHandler textbox.TextChanged, AddressOf RecordChanged
                AddHandler textbox.GotFocus, AddressOf OnTextBoxFocus
                AddHandler textbox.LostFocus, AddressOf OnTextBoxLostFocus
                AddHandler textbox.TextChanged, AddressOf OnTextBoxTextChanged

            Case "ComboBox"
                Dim combo As ComboBox = CType(control, ComboBox)
                AddHandler combo.SelectedValueChanged, AddressOf RecordChanged
                AddHandler combo.SelectedValueChanged, AddressOf OnComboBoxValueChanged
                AddHandler combo.TextChanged, AddressOf RecordChanged
                AddHandler combo.GotFocus, AddressOf OnComboBoxFocus
                AddHandler combo.LostFocus, AddressOf OnComboBoxLostFocus
            Case "RadioButton"
                Dim radiobutton As RadioButton = CType(control, RadioButton)
                AddHandler radiobutton.CheckedChanged, AddressOf RecordChanged
            Case "CheckBox"
                Dim checkbox As CheckBox = CType(control, CheckBox)
                AddHandler checkbox.CheckedChanged, AddressOf RecordChanged
            Case "PictureBox"
                Dim picturebox As PictureBox = CType(control, PictureBox)
                AddHandler picturebox.BackgroundImageChanged, AddressOf RecordChanged
            Case "DateEdit"
                Dim datetimepick As DevExpress.XtraEditors.DateEdit = CType(control, DevExpress.XtraEditors.DateEdit)
                AddHandler datetimepick.DateTimeChanged, AddressOf RecordChanged
            Case "ListBoxControl"
                Dim listbox As DevExpress.XtraEditors.ListBoxControl = CType(control, DevExpress.XtraEditors.ListBoxControl)
                AddHandler listbox.SelectedValueChanged, AddressOf RecordChanged
            Case "CheckedListBoxControl"
                Dim chklistbox As DevExpress.XtraEditors.CheckedListBoxControl = CType(control, DevExpress.XtraEditors.CheckedListBoxControl)
                AddHandler chklistbox.ItemCheck, AddressOf RecordChanged
            Case "DataGridView"
                Dim gridview As DataGridView = CType(control, DataGridView)
                AddHandler gridview.RowsAdded, AddressOf RecordChanged
                AddHandler gridview.CellValueChanged, AddressOf RecordChanged
                AddHandler gridview.RowsRemoved, AddressOf RecordChanged
        End Select
    End Sub

    Private Sub SetDragDropHandler(groupbox As GroupBox)
        If Not IsNothing(_group_box_drag_drop_handler) Then
            AddHandler groupbox.DragDrop, Me._group_box_drag_drop_handler
            AddHandler groupbox.DragEnter, AddressOf Me.GroupBoxDragEnter
        End If
    End Sub

    Private Sub GroupBoxDragEnter(sender As Object, e As DragEventArgs)
        ' Check the format of the data being dropped. 
        If (e.Data.GetDataPresent(DataFormats.Text)) Then
            ' Display the copy cursor. 
            e.Effect = DragDropEffects.Copy
        Else
            ' Display the no-drop cursor. 
            e.Effect = DragDropEffects.None
        End If
    End Sub

    Private Sub selectAll_Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim menu As ContextMenuStrip = item.Owner
        Dim chklb As DevExpress.XtraEditors.CheckedListBoxControl = menu.SourceControl

        chklb.CheckAll()
    End Sub

    Private Sub deselectAll_Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim menu As ContextMenuStrip = item.Owner
        Dim chklb As DevExpress.XtraEditors.CheckedListBoxControl = menu.SourceControl

        chklb.UnCheckAll()
    End Sub

    Private Sub itemAdd_Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim menu As ContextMenuStrip = item.Owner
        Dim pb As PictureBox = menu.SourceControl

        Dim dialog As New OpenFileDialog()
        dialog.Filter = "Bilddateien|*.png;*.jpg;*.jpeg"

        If dialog.ShowDialog() = DialogResult.OK Then
            pb.BackgroundImageLayout = ImageLayout.Zoom
            pb.BackgroundImage = CType(Drawing.Image.FromFile(dialog.FileName, True), Bitmap)
        End If
    End Sub

    Private Sub itemDel_Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim menu As ContextMenuStrip = item.Owner
        Dim pb As PictureBox = menu.SourceControl

        Dim answer = MessageBox.Show("Wollen sie dieses Bild wirklich löschen?", "Bild löschen", MessageBoxButtons.YesNo)

        If answer = DialogResult.Yes Then
            pb.BackgroundImage = Nothing
        End If
    End Sub

    Private Sub itemSave_Click(sender As Object, e As EventArgs)
        Dim item As ToolStripMenuItem = DirectCast(sender, ToolStripMenuItem)
        Dim menu As ContextMenuStrip = item.Owner
        Dim pb As PictureBox = menu.SourceControl

        If IsNothing(pb.BackgroundImage) Then
            MsgBox("Kein Bild ausgewählt!", MsgBoxStyle.Exclamation)
            Exit Sub
        End If

        Dim dialog As New SaveFileDialog()
        dialog.Filter = "PNG-Bilddateien|*.png|JPEG-Bilddateien|*.jpg"
        Try
            If dialog.ShowDialog() = DialogResult.OK Then
                Dim filename As String = dialog.FileName
                Dim ext As String = System.IO.Path.GetExtension(filename)

                Select Case ext
                    Case ".png"
                        pb.BackgroundImage.Save(filename, System.Drawing.Imaging.ImageFormat.Png)
                    Case ".jpg"
                        pb.BackgroundImage.Save(filename, System.Drawing.Imaging.ImageFormat.Jpeg)
                End Select
            End If
        Catch ex As Exception
            MsgBox("Fehler beim Speichern des Bildes:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub

    ' +++ Panel Interaction +++
    Private Sub AddToPanel(control As Control)
        _master_panel.Controls.Add(control)
    End Sub
    ' +++ GroupBox Interaction +++
    Private Sub AddToGroupBox(Parent As GroupBox, Child As Control)
        Parent.Controls.Add(Child)
    End Sub

    Private Sub RemoveFromPanel(control As Control)
        Dim controls As Control.ControlCollection = Me._master_panel.Controls
        controls.Remove(control)
    End Sub

    ' +++ Constructor +++
    Public Sub New(MasterPanel As Panel,
                   MouseDownHandler As MouseEventHandler,
                   MouseUpHandler As MouseEventHandler,
                   MouseMoveHandler As MouseEventHandler,
                   MouseClickHandler As EventHandler,
                   GroupBoxDragDropHandler As DragEventHandler)

        Me._master_panel = MasterPanel
        Me._mouse_down_handler = MouseDownHandler
        Me._mouse_up_handler = MouseUpHandler
        Me._mouse_move_handler = MouseMoveHandler
        Me._mouse_click_handler = MouseClickHandler
        Me._group_box_drag_drop_handler = GroupBoxDragDropHandler
    End Sub

    Public Sub New(MasterPanel As Panel)
        Me._master_panel = MasterPanel
    End Sub

    ' +++ Public Properties +++
    Public Property CurrentControl As Control
        Get
            Return Me._current_control
        End Get
        Set(control As Control)
            Me._current_control = control
        End Set
    End Property

    Public Property BeginLocation As Point
        Get
            Return _begin_location
        End Get
        Set(value As Point)
            _begin_location = value
        End Set
    End Property

    Public Property EndLocation As Point
        Get
            Return _end_location
        End Get
        Set(value As Point)
            _end_location = value
        End Set
    End Property

    Public ReadOnly Property AllControls As Control.ControlCollection
        Get
            Return _master_panel.Controls
        End Get
    End Property
    Public ReadOnly Property MasterPanel As Panel
        Get
            Return _master_panel
        End Get
    End Property

    ' =========================
    ' Textbox Format Handlers
    ' =========================
    Private Sub AddTextHandler(control As TextBox, format As String)
        If format = "Currency" Then
            AddHandler control.Leave, AddressOf Textbox_Currency_Handler
        ElseIf format = "Decimal" Then
            AddHandler control.Leave, AddressOf TextBox_Decimal_Handler
        End If
    End Sub

    Private Sub AddComboHandler(control As ComboBox, format As String)
        If format = "Currency" Then
            AddHandler control.Leave, AddressOf Combo_Currency_Handler
        ElseIf format = "Decimal" Then
            AddHandler control.Leave, AddressOf Combo_Decimal_Handler
        End If
        AddHandler control.KeyUp, AddressOf AutoCompleteCombo_KeyUp
    End Sub

    Private Sub Textbox_Currency_Handler(sender As Object, e As EventArgs)
        Dim control As TextBox = DirectCast(sender, TextBox)
        Dim value As Decimal
        If Decimal.TryParse(control.Text.Trim(), value) Then
            'control.Text = value.ToString("c")
            'control.SelectionStart = control.SelectionStart + 1
            control.Text = FormatCurrency(control.Text)
            'value = FormatNumber(value, -1, TriState.UseDefault, TriState.UseDefault, TriState.True)
            'control.Text = value.ToString("n")
        End If
    End Sub

    Private Sub TextBox_Decimal_Handler(sender As Object, e As EventArgs)
        Dim control As TextBox = DirectCast(sender, TextBox)
        Dim value As Decimal
        If Decimal.TryParse(control.Text.Trim(), value) Then
            control.Text = value.ToString("###,###")
        End If
    End Sub

    Private Sub Combo_Currency_Handler(sender As Object, e As EventArgs)
        Dim control As ComboBox = DirectCast(sender, ComboBox)
        Dim value As Decimal
        If Decimal.TryParse(control.Text.Trim(), value) Then
            control.Text = value.ToString("c")
            control.SelectionStart = control.SelectionStart + 1
            'value = FormatNumber(value, -1, TriState.UseDefault, TriState.UseDefault, TriState.True)
            'control.Text = value.ToString("n")
        End If
    End Sub

    Private Sub Combo_Decimal_Handler(sender As Object, e As EventArgs)
        Dim control As ComboBox = DirectCast(sender, ComboBox)
        Dim value As Decimal
        If Decimal.TryParse(control.Text.Trim(), value) Then
            control.Text = value.ToString("###,###")
        End If
    End Sub

    ' +++ Public Helper Methods +++
    Public Function GetCursorPosition() As Point
        Return Me._master_panel.PointToClient(Cursor.Position)
    End Function

    Public Function GetControlByName(name As String)
        For Each c In _master_panel.Controls
            If c.name = name Then
                Return c
            End If
        Next
        Return Nothing
    End Function

    Public Sub SetActiveColor(ActiveControl As Control)
        Dim ActiveColor As Color = Color.DarkOrange
        Dim CurrentType As String = ActiveControl.GetType.ToString

        Select Case CurrentType
            Case "System.Windows.Forms.TextBox"
                ActiveControl.BackColor = ActiveColor
            Case "System.Windows.Forms.ComboBox"
                ActiveControl.BackColor = ActiveColor
            Case "System.Windows.Forms.Label"
                ActiveControl.BackColor = ActiveColor
            Case "System.Windows.Forms.CheckBox"
                ActiveControl.BackColor = ActiveColor
            Case "System.Windows.Forms.Button"
                ActiveControl.BackColor = ActiveColor
            Case "System.Windows.Forms.DataGridView"
                Dim current As DataGridView = DirectCast(ActiveControl, DataGridView)
                current.BackgroundColor = ActiveColor
            Case "DevExpress.XtraEditors.DateEdit"
                ActiveControl.BackColor = ActiveColor
            Case "System.Window.Forms.GroupBox"
                ActiveControl.BackColor = ActiveColor
            Case "System.Windows.Forms.PictureBox"
                ActiveControl.BackColor = ActiveColor
        End Select
    End Sub

    Public Sub ResetActiveColor(ActiveControl As Control)
        For Each inctrl As Control In Me._master_panel.Controls
            If inctrl.Name <> ActiveControl.Name Then
                Dim Type As String = inctrl.GetType.ToString
                Select Case Type
                    Case "System.Windows.Forms.TextBox"
                        inctrl.BackColor = Color.White
                    Case "System.Windows.Forms.ComboBox"
                        inctrl.BackColor = Color.White
                    Case "System.Windows.Forms.Label"
                        inctrl.BackColor = Color.Transparent
                    Case "System.Windows.Forms.CheckBox"
                        inctrl.BackColor = Color.Transparent
                    Case "System.Windows.Forms.DataGridView"
                        Dim ctrl As DataGridView = DirectCast(inctrl, DataGridView)
                        ctrl.BackgroundColor = SystemColors.ControlDark
                    Case "DevExpress.XtraEditors.DateEdit"
                        inctrl.BackColor = Color.White
                    Case "System.Windows.Forms.Button"
                        inctrl.BackColor = SystemColors.Control
                    Case "System.Windows.Forms.GroupBox"
                        inctrl.BackColor = SystemColors.Control
                    Case "System.Windows.Forms.PictureBox"
                        inctrl.BackColor = SystemColors.ControlDark

                        For Each gbctrl As Control In inctrl.Controls
                            If gbctrl.Name <> ActiveControl.Name Then
                                Dim gbType As String = gbctrl.GetType.ToString
                                Select Case gbType
                                    Case "System.Windows.Forms.TextBox"
                                        gbctrl.BackColor = Color.White
                                    Case "System.Windows.Forms.ComboBox"
                                        gbctrl.BackColor = Color.White
                                    Case "System.Windows.Forms.Label"
                                        gbctrl.BackColor = Color.Transparent
                                    Case "System.Windows.Forms.CheckBox"
                                        gbctrl.BackColor = Color.Transparent
                                    Case "System.Windows.Forms.DataGridView"
                                        Dim ctrl As DataGridView = DirectCast(gbctrl, DataGridView)
                                        ctrl.BackgroundColor = SystemColors.ControlDark
                                    Case "DevExpress.XtraEditors.DateEdit"
                                        gbctrl.BackColor = Color.White
                                    Case "System.Windows.Forms.Button"
                                        gbctrl.BackColor = SystemColors.Control
                                    Case "System.Windows.Forms.PictureBox"
                                        inctrl.BackColor = SystemColors.ControlDark
                                End Select
                            End If
                        Next
                End Select
            End If
        Next
    End Sub

    Public Sub SetAllActiveColor()
        SetActiveColor(_current_control)
        ' Remove Active Color from all other Controls
        ResetActiveColor(_current_control)
    End Sub
    ' +++ Public Methods +++
    Public Sub ClearControls()
        Me._master_panel.Controls.Clear()
    End Sub

    Public Sub RemoveControl(name As String)
        For Each ctrl As Control In Me._master_panel.Controls
            If (name = ctrl.Name) Then
                Me._master_panel.Controls.Remove(ctrl)
                Exit Sub
            End If
        Next
    End Sub
    Public Sub AddLabel(id As Integer,
                        name As String,
                        text As String,
                        x As Integer,
                        y As Integer,
                        fontfamily As String,
                        fontcolor As Integer,
                        fontsize As Integer,
                        fontstyle As Integer,
                        sqlcommand As String,
                        _new As Boolean,
                        Optional parent As GroupBox = Nothing,
                        Optional _designMode As Boolean = False)

        Try
            Dim control As Label = New Label
            Dim defaultSize As Size = New Size(200, 27)

            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            control.Tag = metadata

            control.Name = name
            control.Text = text
            control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.ForeColor = IntToColor(fontcolor)
            control.AutoSize = True

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = defaultSize
            End If

            If _designMode = True Then
                control.Cursor = Cursors.Hand
            End If

            'SQL-Command vorhanden also Ausführen des SQL
            If sqlcommand.Length > 1 Then
                Dim result = ClassDatabase.Execute_Scalar(sqlcommand)
                If Not IsNothing(result) Then
                    If Not IsDBNull(result) Then
                        If Not IsNothing(result) Then
                            control.Text = result.ToString
                        End If
                    End If
                End If
            End If

            Me.SetEventHandlers(control)
            Me.CurrentControl = DirectCast(control, Label)

            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If

        Catch ex As Exception
            MsgBox("Error in AddLabel: " + vbNewLine + ex.Message)
        End Try

    End Sub

    Public Sub AddTextBox(id As Integer,
                          name As String,
                          x As Integer,
                          y As Integer,
                          fontfamily As String,
                          fontcolor As Integer,
                          fontsize As Integer,
                          fontstyle As Integer,
                          tabindex As Integer,
                          tabstop As Integer,
                          vwidth As Integer,
                          vheight As Integer,
                          multiline As Boolean,
                          read_only As Boolean,
                          required As Boolean,
                          format As String,
                          _new As Boolean,
                          Optional parent As GroupBox = Nothing,
                          Optional _designMode As Boolean = False)
        Try
            Dim control As New TextBox
            Dim defaultSize As Size = New Size(200, 27)


            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            metadata.Required = required
            control.Tag = metadata

            control.Name = name
            control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.ForeColor = IntToColor(fontcolor)
            control.TabIndex = tabindex
            control.TabStop = tabstop
            control.BorderStyle = BorderStyle.FixedSingle
            control.ReadOnly = read_only

            AddTextHandler(DirectCast(control, Control), format)

            'Console.WriteLine("setting tabindex of control " & name & " to " & tabindex)

            If multiline = True Then
                control.Multiline = True
                control.AcceptsReturn = True
                control.AcceptsTab = True
                control.ScrollBars = ScrollBars.Vertical
            End If

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            If _designMode = True Then
                control.Cursor = Cursors.Hand
            End If

            If Not read_only Or _designMode Then
                Me.SetEventHandlers(control)
            End If


            Me.CurrentControl = DirectCast(control, TextBox)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If

        Catch ex As Exception
            MsgBox("Error in AddTextBox: " + vbNewLine + ex.Message)
        End Try


    End Sub
    Public Sub AddCheckBox(id As Integer,
                           name As String,
                           text As String,
                           Checked As Boolean,
                           x As Integer,
                           y As Integer,
                           fontfamily As String,
                           fontcolor As Integer,
                           fontsize As Integer,
                           fontstyle As Integer,
                           tabindex As Integer,
                           tabstop As Boolean,
                           vwidth As Integer,
                           vheight As Integer,
                           _new As Boolean,
                           read_only As Boolean,
                           required As Boolean,
                           Optional parent As GroupBox = Nothing,
                           Optional _designMode As Boolean = False)
        Try
            Dim control As New CheckBox
            Dim defaultSize As Size = New Size(150, 27)

            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            metadata.Required = required
            control.Tag = metadata

            control.Checked = Checked
            control.Name = name
            control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.ForeColor = IntToColor(fontcolor)
            control.Text = text
            control.TabIndex = tabindex
            control.TabStop = tabstop
            control.AutoCheck = True
            If _designMode = True Then
                control.AutoCheck = False
                control.Cursor = Cursors.Hand
            Else
                control.AutoCheck = True
            End If

            If Not _designMode And read_only Then
                control.Enabled = Not read_only
            End If

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            Me.SetEventHandlers(control)
            Me.CurrentControl = DirectCast(control, CheckBox)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If
        Catch ex As Exception
            MsgBox("Error in AddCheckBox: " + vbNewLine + ex.Message)
        End Try

    End Sub
    Public Sub AddRadioButton(id As Integer,
                              name As String,
                          text As String,
                          Checked As Boolean,
                          x As Integer,
                          y As Integer,
                          fontfamily As String,
                          fontcolor As Integer,
                          fontsize As Integer,
                          fontstyle As Integer,
                          tabindex As Integer,
                          tabstop As Boolean,
                          vwidth As Integer,
                          vheight As Integer,
                          _new As Boolean,
                          read_only As Boolean,
                          required As Boolean,
                           Optional parent As GroupBox = Nothing,
                          Optional _designMode As Boolean = False)
        Try
            Dim control As New RadioButton
            Dim defaultSize As Size = New Size(150, 27)

            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            metadata.Required = required
            control.Tag = metadata

            control.Name = name
            control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.ForeColor = IntToColor(fontcolor)
            control.Text = text
            control.TabIndex = tabindex
            control.TabStop = tabstop
            control.AutoCheck = True
            control.Checked = Checked

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            If Not _designMode And read_only Then
                control.Enabled = Not read_only
            End If

            If _designMode = True Then
                control.Cursor = Cursors.Hand
            End If

            Me.SetEventHandlers(control)
            Me.CurrentControl = DirectCast(control, RadioButton)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If
        Catch ex As Exception
            MsgBox("Error in AddRadioButton: " + vbNewLine + ex.Message)
        End Try

    End Sub
    Public Sub AddComboBox(id As Integer,
                           name As String,
                           x As Integer,
                           y As Integer,
                           fontfamily As String,
                           fontcolor As Integer,
                           fontsize As Integer,
                           fontstyle As Integer,
                           tabindex As Integer,
                           tabstop As Boolean,
                           vwidth As Integer,
                           vheight As Integer,
                           vformat As String,
                           _new As Boolean,
                           read_only As Boolean,
                           required As Boolean,
                           static_list As String,
                           sqlcommand As String,
                           Optional parent As GroupBox = Nothing,
                           Optional _designMode As Boolean = False)
        Try
            Dim control As New ComboBox
            Dim defaultSize As Size = New Size(120, 24)

            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            metadata.Required = required
            control.Tag = metadata

            control.Name = name
            control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.ForeColor = IntToColor(fontcolor)
            control.TabIndex = tabindex
            control.TabStop = tabstop
            control.Parent = _master_panel
            control.DropDownStyle = ComboBoxStyle.DropDown
            control.FormattingEnabled = True
            control.AutoCompleteMode = AutoCompleteMode.Append
            control.AutoCompleteSource = AutoCompleteSource.ListItems

            If (Not _designMode And read_only) Then
                control.Enabled = Not read_only
            End If

            AddComboHandler(control, vformat)

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            ' Wenn statische liste vorhanden, werte splitten und einfügen
            If static_list.Length > 0 Then
                Dim items() As String = static_list.Split(";")
                For Each item As String In items
                    control.Items.Add(item)
                Next
            End If

            Me.SetEventHandlers(control)
            Me.CurrentControl = DirectCast(control, ComboBox)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If
        Catch ex As Exception
            MsgBox("Error in AddComboBox: " + vbNewLine + ex.Message)
        End Try

    End Sub
    Public Sub AutoCompleteCombo_KeyUp(ByVal cbo As ComboBox, ByVal e As KeyEventArgs)
        ''Allow select keys without Autocompleting
        Select Case e.KeyCode
            Case Keys.Back, Keys.Left, Keys.Right, Keys.Up, Keys.Delete, Keys.Down
                Return
        End Select

        Dim iFoundIndex As Integer
        iFoundIndex = cbo.FindStringExact(cbo.Text)
        'cbo.SelectedIndex = iFoundIndex
        'Dim sTypedText As String
        'Dim iFoundIndex As Integer
        'Dim oFoundItem As Object
        'Dim sFoundText As String
        'Dim sAppendText As String



        ''Get the Typed Text and Find it in the list
        'sTypedText = cbo.Text
        'iFoundIndex = cbo.FindString(sTypedText)

        ''If we found the Typed Text in the list then Autocomplete
        'If iFoundIndex >= 0 Then

        '    'Get the Item from the list (Return Type depends if Datasource was bound 
        '    ' or List Created)
        '    oFoundItem = cbo.Items(iFoundIndex)

        '    'Use the ListControl.GetItemText to resolve the Name in case the Combo 
        '    ' was Data bound
        '    sFoundText = cbo.GetItemText(oFoundItem)

        '    'Append then found text to the typed text to preserve case
        '    sAppendText = sFoundText.Substring(sTypedText.Length)
        '    cbo.Text = sTypedText & sAppendText

        '    'Select the Appended Text
        '    cbo.SelectionStart = sTypedText.Length
        '    cbo.SelectionLength = sAppendText.Length

        'End If

    End Sub
    Public Sub AutoCompleteCombo_Leave(ByVal cbo As ComboBox)
        Dim iFoundIndex As Integer
        iFoundIndex = cbo.FindStringExact(cbo.Text)
        cbo.SelectedIndex = iFoundIndex
    End Sub
    Public Sub AddDateTimePicker(id As Integer,
                                name As String,
                             x As Integer,
                             y As Integer,
                             fontfamily As String,
                             fontsize As Integer,
                             fontstyle As Integer,
                             tabindex As Integer,
                             tabstop As Boolean,
                             vwidth As Integer,
                             vheight As Integer,
                             read_only As Boolean,
                             required As Boolean,
                             _new As Boolean,
                              Optional parent As GroupBox = Nothing,
                             Optional _designMode As Boolean = False)
        Try
            Dim control As New DevExpress.XtraEditors.DateEdit
            'Dim control As New DateTimePicker
            Dim defaultSize As Size = New Size(90, 20)

            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            metadata.Required = required
            control.Tag = metadata

            control.Name = name
            'control.Format = DateTimePickerFormat.Short
            'control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            'control.CalendarFont = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.TabIndex = tabindex
            control.TabStop = tabstop
            control.Parent = _master_panel
            control.Properties.NullDate = DateTime.MinValue
            control.Properties.NullText = String.Empty
            control.Properties.ReadOnly = read_only

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            If Not read_only Or _designMode Then
                Me.SetEventHandlers(control)
            End If

            'Me.CurrentControl = DirectCast(control, DateTimePicker)
            Me.CurrentControl = DirectCast(control, DevExpress.XtraEditors.DateEdit)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If
        Catch ex As Exception
            MsgBox("Error in AddDateTimePicker: " + vbNewLine + ex.Message)
        End Try

    End Sub
    Public Sub AddDataGridView(id As Integer,
                               name As String,
                               x As Integer,
                               y As Integer,
                               vwidth As Integer,
                               vheight As Integer,
                               _new As Boolean,
                               read_only As Boolean,
                               required As Boolean,
                               columnTitle As String,
                               Optional parent As GroupBox = Nothing,
                               Optional _designMode As Boolean = False)

        Dim control As New DataGridView
        Dim column As New DataGridViewTextBoxColumn
        Dim defaultSize = New Size(130, 150)

        Dim metadata As New ClassControlMetadata()
        metadata.Id = id
        metadata.Name = name
        metadata.Required = required
        control.Tag = metadata

        control.Name = name
        control.BackgroundColor = SystemColors.ControlDark
        control.AllowUserToAddRows = True
        control.AllowUserToDeleteRows = True
        control.AllowUserToResizeColumns = False
        control.AllowUserToResizeRows = False
        control.Parent = _master_panel
        control.ReadOnly = read_only

        column.HeaderText = columnTitle
        column.Name = "column1"
        control.Columns.Add(column)

        If _new And IsNothing(parent) Then
            control.Location = Me.GetCursorPosition()
            control.Size = defaultSize
        ElseIf _new And Not IsNothing(parent) Then
            Dim cursor = Me.GetCursorPosition()

            control.Location = New Point(cursor.X - parent.Location.X,
                                         cursor.Y - parent.Location.Y)
        Else
            control.Location = New Point(x, y)
            control.Size = New Size(vwidth, vheight)
        End If

        If _designMode = True Then
            control.Cursor = Cursors.Hand
        End If

        Me.SetEventHandlers(control)
        Me.CurrentControl = DirectCast(control, DataGridView)
        If Not IsNothing(parent) Then
            control.Parent = parent
            Me.AddToGroupBox(parent, control)
        Else
            control.Parent = _master_panel
            Me.AddToPanel(control)
        End If
    End Sub
    Public Sub AddPictureBox(id As Integer,
                             name As String,
                             x As Integer,
                             y As Integer,
                             vwidth As Integer,
                             vheight As Integer,
                             _new As Boolean,
                             read_only As Boolean,
                             required As Boolean,
                             Optional parent As GroupBox = Nothing,
                             Optional _designMode As Boolean = False)

        Dim control As New PictureBox
        Dim defaultSize = New Size(200, 100)
        Dim ctx As New ContextMenuStrip()

        Dim itemAdd As New ToolStripMenuItem()
        Dim itemDel As New ToolStripMenuItem()
        Dim itemSave As New ToolStripMenuItem()

        itemAdd.Text = "Bild auswählen.."
        itemDel.Text = "Bild löschen"
        itemSave.Text = "Bild speichern unter.."

        AddHandler itemAdd.Click, AddressOf itemAdd_Click
        AddHandler itemDel.Click, AddressOf itemDel_Click
        AddHandler itemSave.Click, AddressOf itemSave_Click
        'Nur bei ReadOnly alle Auswahlmöglichkeiten
        If read_only = False Then
            ctx.Items.Add(itemAdd)
            ctx.Items.Add(itemDel)
        End If
        ctx.Items.Add(itemSave)

        Dim metadata As New ClassControlMetadata()
        metadata.Id = id
        metadata.Name = name
        metadata.Required = required
        control.Tag = metadata

        control.Name = name
        control.Parent = _master_panel
        control.BorderStyle = BorderStyle.FixedSingle
        control.ContextMenuStrip = ctx
        control.BackgroundImage = My.Resources.ImageListControl_683
        control.BackgroundImageLayout = ImageLayout.Zoom

        If _new And IsNothing(parent) Then
            control.Location = Me.GetCursorPosition()
            control.Size = defaultSize
        ElseIf _new And Not IsNothing(parent) Then
            Dim cursor = Me.GetCursorPosition()

            control.Location = New Point(cursor.X - parent.Location.X,
                                         cursor.Y - parent.Location.Y)
        Else
            control.Location = New Point(x, y)
            control.Size = New Size(vwidth, vheight)
        End If

        If _designMode = True Then
            control.Cursor = Cursors.Hand
        End If

        Me.SetEventHandlers(control)
        Me.CurrentControl = DirectCast(control, PictureBox)
        If Not IsNothing(parent) Then
            control.Parent = parent
            Me.AddToGroupBox(parent, control)
        Else
            control.Parent = _master_panel
            Me.AddToPanel(control)
        End If
    End Sub
    Public Sub AddGroupBox(id As Integer,
                           name As String,
                           Caption As String,
                           x As Integer,
                           y As Integer,
                           vwidth As Integer,
                           vheight As Integer,
                           backcolor As Integer,
                           fontcolor As Integer,
                           fontfamily As String,
                           fontsize As Integer,
                           fontstyle As Integer,
                           _new As Boolean,
                           Optional parent As GroupBox = Nothing,
                           Optional _designMode As Boolean = False)

        Dim control As New GroupBox
        Dim defaultSize = New Size(200, 100)

        Dim metadata As New ClassControlMetadata()
        metadata.Id = id
        metadata.Name = name
        control.Tag = metadata

        control.Name = name
        control.Parent = _master_panel
        control.Text = Caption
        'control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
        control.ForeColor = IntToColor(fontcolor)
        control.BackColor = IntToColor(backcolor)

        If _new And IsNothing(parent) Then
            control.Location = Me.GetCursorPosition()
            control.Size = defaultSize
        ElseIf _new And Not IsNothing(parent) Then
            Dim cursor = Me.GetCursorPosition()

            control.Location = New Point(cursor.X - parent.Location.X,
                                         cursor.Y - parent.Location.Y)
        Else
            control.Location = New Point(x, y)
            control.Size = New Size(vwidth, vheight)
        End If

        If _designMode = True Then
            control.Cursor = Cursors.Hand
        End If

        control.AllowDrop = True

        Me.SetEventHandlers(control)
        Me.SetDragDropHandler(control)
        Me.CurrentControl = DirectCast(control, GroupBox)
        If Not IsNothing(parent) Then
            control.Parent = parent
            Me.AddToGroupBox(parent, control)
        Else
            control.Parent = _master_panel
            Me.AddToPanel(control)
        End If
    End Sub
    Public Sub FunctionAddAppointment(id As Integer,
                                      name As String,
                                      text As String,
                                      x As Integer,
                                      y As Integer,
                                      vwidth As Integer,
                                      vheight As Integer,
                                      _new As Boolean,
                                       Optional parent As GroupBox = Nothing,
                                      Optional _designMode As Boolean = False)
        Try
            Dim control As Button = New Button
            Dim defaultSize As Size = New Size(200, 27)

            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            control.Tag = metadata

            control.Name = name
            control.Text = text
            control.TabStop = False
            control.Image = My.Resources.calendar_add
            control.ImageAlign = ContentAlignment.MiddleRight
            control.TextAlign = ContentAlignment.MiddleLeft

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            If _designMode = True Then
                control.Cursor = Cursors.Hand
            End If

            Me.SetEventHandlers(control)
            Me.CurrentControl = DirectCast(control, Button)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If

        Catch ex As Exception
            MsgBox("Error in FunctionAddAppointment: " + vbNewLine + ex.Message)
        End Try


    End Sub
    Public Sub FunctionAddFormData(id As Integer,
                                   name As String,
                                   text As String,
                                   x As Integer,
                                   y As Integer,
                                   vwidth As Integer,
                                   vheight As Integer,
                                   _new As Boolean,
                                    Optional parent As GroupBox = Nothing,
                                   Optional _designMode As Boolean = False)
        Try
            Dim control As Button = New Button
            Dim defaultSize As Size = New Size(30, 21)

            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            control.Tag = metadata

            control.Name = name
            control.Text = ""
            control.TabStop = False
            control.Image = My.Resources.add1

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            If _designMode = True Then
                control.Cursor = Cursors.Hand
            End If

            Me.SetEventHandlers(control)
            Me.CurrentControl = DirectCast(control, Button)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If

        Catch ex As Exception
            MsgBox("Fehler: " + vbNewLine + ex.Message)
        End Try
    End Sub
    Public Sub AddCheckedListBox(id As Integer,
                                 name As String,
                          x As Integer,
                          y As Integer,
                          fontfamily As String,
                          fontcolor As Integer,
                          fontsize As Integer,
                          fontstyle As Integer,
                          tabindex As Integer,
                          tabstop As Boolean,
                          vwidth As Integer,
                          vheight As Integer,
                         _new As Boolean,
                         read_only As Boolean,
                         required As Boolean,
                         static_list As String,
                          sqlcommand As String,
                           Optional parent As GroupBox = Nothing,
                          Optional _designMode As Boolean = False)
        Try
            Dim control As New DevExpress.XtraEditors.CheckedListBoxControl
            Dim defaultSize As Size = New Size(180, 140)

            'control.CheckOnClick = True
            ' control.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Style3
            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            metadata.Required = required
            control.Tag = metadata

            control.Name = name
            control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.ForeColor = IntToColor(fontcolor)
            control.TabIndex = tabindex
            control.TabStop = tabstop
            control.Parent = _master_panel

            If Not _designMode And read_only Then
                control.Enabled = Not read_only
            End If

            Dim ctx As New ContextMenuStrip()

            Dim selectAll As New ToolStripMenuItem()
            Dim deselectAll As New ToolStripMenuItem()

            selectAll.Text = "Alle auswählen"
            deselectAll.Text = "Keine auswählen"

            AddHandler selectAll.Click, AddressOf selectAll_Click
            AddHandler deselectAll.Click, AddressOf deselectAll_Click

            ctx.Items.Add(selectAll)
            ctx.Items.Add(deselectAll)

            control.ContextMenuStrip = ctx

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            'SQL-Command vorhanden?
            If sqlcommand.Length > 1 Then
                'Ja also überprüfen ob parametrisiert??
                If Not sqlcommand.ToString.Contains("@") Then
                    'SQL-Command vorhanden also Ausführen des SQL
                    Dim DT_ListBox As DataTable = ClassDatabase.Return_Datatable(sqlcommand)
                    If DT_ListBox Is Nothing = False Then
                        If DT_ListBox.Rows.Count > 0 Then
                            control.DataSource = DT_ListBox
                            control.DisplayMember = DT_ListBox.Columns(1).ColumnName
                            control.ValueMember = DT_ListBox.Columns(0).ColumnName
                        End If
                    End If
                End If
            End If

            ' Wenn statische liste vorhanden, werte splitten und einfügen
            If static_list.Length > 0 Then
                Dim items() As String = static_list.Split(";")
                For Each item As String In items
                    control.Items.Add(item)
                Next
            End If

            Me.SetEventHandlers(control)
            Me.CurrentControl = DirectCast(control, DevExpress.XtraEditors.CheckedListBoxControl)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If
        Catch ex As Exception
            MsgBox("Error in AddCheckedListBox: " + vbNewLine + ex.Message)
        End Try
    End Sub
    Public Sub AddListBox(id As Integer,
                          name As String,
                          x As Integer,
                          y As Integer,
                          fontfamily As String,
                          fontcolor As Integer,
                          fontsize As Integer,
                          fontstyle As Integer,
                          tabindex As Integer,
                          tabstop As Boolean,
                          vwidth As Integer,
                          vheight As Integer,
                         _new As Boolean,
                         read_only As Boolean,
                         required As Boolean,
                         static_list As String,
                          sqlcommand As String,
                           Optional parent As GroupBox = Nothing,
                          Optional _designMode As Boolean = False)
        Try
            Dim control As New DevExpress.XtraEditors.ListBoxControl
            Dim defaultSize As Size = New Size(180, 140)

            'control.CheckOnClick = True
            ' control.CheckStyle = DevExpress.XtraEditors.Controls.CheckStyles.Style3

            Dim metadata As New ClassControlMetadata()
            metadata.Id = id
            metadata.Name = name
            metadata.Required = required
            control.Tag = metadata

            control.Name = name
            control.Font = New Font(fontfamily, fontsize, CType(fontstyle, FontStyle))
            control.ForeColor = IntToColor(fontcolor)
            control.TabIndex = tabindex
            control.TabStop = tabstop
            control.Parent = _master_panel

            If Not _designMode And read_only Then
                control.Enabled = Not read_only
            End If

            If _new And IsNothing(parent) Then
                control.Location = Me.GetCursorPosition()
                control.Size = defaultSize
            ElseIf _new And Not IsNothing(parent) Then
                Dim cursor = Me.GetCursorPosition()

                control.Location = New Point(cursor.X - parent.Location.X,
                                             cursor.Y - parent.Location.Y)
            Else
                control.Location = New Point(x, y)
                control.Size = New Size(vwidth, vheight)
            End If

            'SQL-Command vorhanden also Ausführen des SQL
            If sqlcommand.Length > 1 Then
                If Not sqlcommand.ToString.Contains("@") Then
                    'SQL-Command vorhanden also Ausführen des SQL
                    Dim DT_ListBox As DataTable = ClassDatabase.Return_Datatable(sqlcommand)
                    If DT_ListBox Is Nothing = False Then
                        If DT_ListBox.Rows.Count > 0 Then
                            control.DataSource = DT_ListBox
                            control.DisplayMember = DT_ListBox.Columns(1).ColumnName
                            control.ValueMember = DT_ListBox.Columns(0).ColumnName
                        End If
                    End If
                End If
            End If

            ' Wenn statische liste vorhanden, werte splitten und einfügen
            If static_list.Length > 0 Then
                Dim items() As String = static_list.Split(";")
                For Each item As String In items
                    control.Items.Add(item)
                Next
            End If

            Me.SetEventHandlers(control)
            Me.CurrentControl = DirectCast(control, DevExpress.XtraEditors.ListBoxControl)
            If Not IsNothing(parent) Then
                control.Parent = parent
                Me.AddToGroupBox(parent, control)
            Else
                control.Parent = _master_panel
                Me.AddToPanel(control)
            End If
        Catch ex As Exception
            MsgBox("Error in AddListBox: " + vbNewLine + ex.Message)
        End Try
    End Sub
End Class