How do I get the SelectedValue of a ComboBox from code?

倖福魔咒の 提交于 2019-12-21 05:41:00

问题


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.


回答1:


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;



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!