【问题标题】:Get currently selected Combobox value and use it as variable获取当前选择的 Combobox 值并将其用作变量
【发布时间】:2011-11-19 12:17:02
【问题描述】:

我的问题是关于 Delphi 7。

我需要获取当前选定的 ComboBox1 值,以便在我的代码中将其用作浮点变量:

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

谢谢!

【问题讨论】:

    标签: delphi combobox tcombobox


    【解决方案1】:

    不确定TryStrToFloat 是否已经在 Delphi 7 中,但如果是,我会这样做。

    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;
    

    【讨论】:

    • 工作,正是我需要的!
    • 嗯,不知道TryStrToFloat(),虽然我一直使用StrToFloatDef(),它在同一个单元(SysUtils)中。 +1
    • @talereader,谢谢。顺便提一句。 TryStrToFloatStrToFloatDef 这两个函数在内部调用 TextToFloat 函数。唯一的区别是他们如何使用它;如果你写例如var Output: Extended; begin if not TryStrToFloat('0.xx', Output) then Output := 0.01; end; 那么你将得到与调用Output := StrToFloatDef('0.xx', 0.01); 相同的结果;)
    【解决方案2】:
    // 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;
    

    【讨论】:

    • 或者更好的TryStrToFloat,你可以使用ComboBox1.Text而不是ComboBox1.Items[ComboBox1.ItemIndex])
    • 代码中多了一个“)”。删除它后,它工作得很好。谢谢!
    • 我个人不喜欢这段代码,因为它使用了对 ComboBox1.ItemIndex 属性的两个引用。我不确定这个属性的 read 方法是做什么的,也许它只是读取一个字段所以没有性能惩罚,但感觉不对。
    • @TLama:访问 ComboBox1.Text 与 ComboBox1.Items[ComboBox1.ItemIndex] 的访问相同。文本可能不在项目列表中。
    【解决方案3】:

    在 Delphi 10.2 Tokyo 我只是这样做:

    [字符串] := ComboBox.Selected.Text

    【讨论】:

    • 这个答案对已经回答的问题没有帮助。
    猜你喜欢
    • 2020-07-20
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多