Search code examples
delphidelphi-xe2firemonkeylivebindings

TDBLookupCombobox FireMonkey


TDBLookupCombobox

Can anyone help me to reproduce TDBLookupCombobox functionality in FireMonkey?


Solution

  • I don't know if there is a better solution but this is what i do:

    Suppose you have Table1 with a Foreign Key to Table2.

    • Make a Lookup field in Table1 using the Foreign Key.
    • Use TBindList to fill the Text property of the Combobox with the looked up field in Table2 and fill the Tag property with the Primary Key of Table2.
    • Use TBindPosition to match the selected text with the lookup field and Selected.Tag with the Foreign Key in Table1.

    edit:

    Check the SourceComponent property of your TBindList and TBindPosition.

    TBindList should point to the BindScopeDB of Table2.

    TBindPosition, instead, to the BindScopeDB of Table1.

    ControlComponent should point to your TComboBox for both.

    When you use TBindList, Format collection expressions refer to the single item inside the ComboBox because it cycles for every row in your Table2 to fill the control. So ControlExpressions are the properties of each item:

    Text, Tag

    Note: you don't need Selected

    and these SourceExpressions:

    FieldByName(LookedUpField).AsString, FieldByName(PK).AsInteger

    Put these expressions in the Format collection.

    TBindPosition, instead, refers always to the whole ComboBox so you need to use Selected. ControlExpressions:

    Selected.Tag SelectedText(Self),

    SourceExpressions:

    FieldByName(FK).AsInteger, FieldByName(LookupField).AsString

    Remember that PosSource collection is used to set "ControlExpressions TO SourceExpressions" assignments while PosControl contains "SourceExpressions TO ControlExpressions" assignments.

    Basically you need two things: change your selected item when Table1 cursor changes and set your FK using the Tag property of the selected item when user changes it.

    So just put these in your PosControl collection:

    SelectedText(Self) ControlExpression

    FieldByName(LookupField).AsString SourceExpression

    and these in your PosSource collection:

    Selected.Tag ControlExpression

    FieldByName(FK).AsInteger SourceExpression

    If you want to make a similar behavior of TDBLookupComboBox you have to put the Table in Edit state when the selected combobox item is changed.

    When I tried Firemonkey some months ago I needed more expressions to update the same field shown in a StringGrid but I don't know if there is a better solution for that. Hope someone else can answer and share his experience about this.

    For more informations look for the examples included with XE2.

    Hope this helped a bit.