I am trying to build something like a TLookupComboBox
using LiveBindings.
I have placed a normal TComboBox
on a VCL form. I also have a data set with some rows that have the two fields id
and text
.
Then I used the LiveBindings editor to create a TBindSourceDB
and a TBindingsList
.
There is just one binding in it:
object BindingsList1: TBindingsList
Methods = <>
OutputConverters = <>
UseAppManager = True
Left = 244
Top = 229
object LinkFillControlToField1: TLinkFillControlToField
Category = 'Quick Bindings'
Control = ComboBox1
Track = True
FillDataSource = BindSourceDB1
FillValueFieldName = 'id'
FillDisplayFieldName = 'text'
AutoFill = True
BufferCount = -1
FillExpressions = <>
end
end
As you can see I have different fields for FillValueFieldName
and FillDisplayFieldName
.
The LiveBindings designer looks like this:
The ComboBox is filled with the values from the field text
, so I think I set it up correctly.
How can I get the SelectedValue
from code?
I could visually bind the value to a TLabel
and then I could read the TLabel.Caption
, but surely there is an easier way?
PS: I do not want to store the value in the DB, otherwise I would just use a TDBLookupComboBox
.
Edit: I have tried to use a TPrototypeBindSource
, but that has no obvious way to access the fields from code. I have also tried to use a second TBindSourceDB
together with a TClientDataSet
which works, but that feels like using a sledgehammer to crack a nut.
You can access the selected value via the corresponding TLinkFillControlToField
:
procedure TForm1.ComboBox1Change(Sender: TObject);
var
SelectedValue: Integer;
begin
if TryStrToInt(LinkFillControlToField1.BindList.GetSelectedValue.AsString, SelectedValue) then
DoSomethingWith(SelectedValue);
end;
Maybe this can help you. you can add a global variable named selectedIndex
, then double click on the combo box. it will bring the ComboBoxChange
event. Then write the code below:
selectedIndex := combobox1.ItemIndex;
来源:https://stackoverflow.com/questions/23712406/how-do-i-get-the-selectedvalue-of-a-combobox-from-code