10

My question is about Delphi 7.

I need to get currently selected ComboBox1 value to use it as Floating point variable in my code:

t:=t+ComboBox1. // Not sure what to write here...

Thank you!

manlio
  • 18,345
  • 14
  • 76
  • 126
enflam3
  • 157
  • 1
  • 2
  • 10

4 Answers4

11

Not sure if the TryStrToFloat is already in Delphi 7, but if yes I would do it this way.

procedure TForm1.ComboBox1Change(Sender: TObject);
var
  Value: Double;
begin
  if TryStrToFloat(ComboBox1.Text, Value) then
    T := T + Value
  else
    ShowMessage('You''ve entered wrong value ...');
end;
TLama
  • 75,147
  • 17
  • 214
  • 392
  • 1
    Worked and was exactly what I needed! – enflam3 Nov 19 '11 at 12:47
  • 1
    Hm, didn't know about `TryStrToFloat()`, although I always used `StrToFloatDef()` which is in the same unit (SysUtils). +1 – binar Dec 21 '11 at 21:36
  • @talereader, thanks. Btw. both functions, [`TryStrToFloat`](http://docwiki.embarcadero.com/VCL/en/SysUtils.TryStrToFloat) and [`StrToFloatDef`](http://docwiki.embarcadero.com/VCL/en/SysUtils.StrToFloatDef) internally calls the [`TextToFloat`](http://docwiki.embarcadero.com/VCL/en/SysUtils.TextToFloat) function. The only difference is how do they use it; if you write e.g. `var Output: Extended; begin if not TryStrToFloat('0.xx', Output) then Output := 0.01; end;` then you will get the same as if you call `Output := StrToFloatDef('0.xx', 0.01);` ;) – TLama Dec 21 '11 at 21:49
5
// ItemIndex is the index of the selected item
// If no item is selected, the value of ItemIndex is -1
if (ComboBox1.ItemIndex >= 0) then
begin
  t := t + StrToFloat(ComboBox1.Items[ComboBox1.ItemIndex]);
end;
splash
  • 13,037
  • 1
  • 44
  • 67
  • 1
    Or better [TryStrToFloat](http://docwiki.embarcadero.com/VCL/en/SysUtils.TryStrToFloat) and you can use `ComboBox1.Text` instead of `ComboBox1.Items[ComboBox1.ItemIndex])` – TLama Nov 19 '11 at 12:25
  • There is one extra ")" in the code. After Removing it, it worked just fine. Thank you! – enflam3 Nov 19 '11 at 12:50
  • Personally I don't like this code because it uses two references to the ComboBox1.ItemIndex property. I am not sure what the read method for this property does, maybe it just reads a field so there is no performane penalty, but it just feels wrong. – dummzeuch Nov 19 '11 at 16:06
  • 3
    @TLama: accessing ComboBox1.Text is *not* the same as ComboBox1.Items[ComboBox1.ItemIndex]). It is possible for the text to not be in the Items list. – dummzeuch Nov 19 '11 at 16:07
1

In Delphi 10.2 Tokyo i just do:

[string] := ComboBox.Selected.Text

0

Nowadays it is ComboBox1.Text; only :)

Dreamer64
  • 923
  • 2
  • 13
  • 30