【问题标题】:iterate over edit box and compare value with previous in Delphi迭代编辑框并将值与 Delphi 中的先前值进行比较
【发布时间】:2012-12-11 21:39:29
【问题描述】:

我正在做一个学校项目,我有 10 个文本框(5 对)。

这个想法是每对的总和最多可以是“3”。所以

[1] [2]

[1] [0]

...

[2] [1]

我认为在“onChange”事件期间检查这个太费时了,所以我决定用一个按钮来检查所有这些。只要任何一对不满足要求,它就会抛出一个 showmessage()。

现在有没有办法检查每一对并检查它们的值是否小于或等于三并且不是负数?我知道我可以通过编写大量代码来手动完成,但我希望尽可能保持干净。

谢谢!

【问题讨论】:

  • 是的,这在 80 年代太耗时了。
  • 我不确定你想说什么
  • 这样做OnChange 甚至不会使您的 CPU 达到 1%,即使您每秒更改 10 次也不行。
  • 不,我的意思是我必须为每个编辑框创建一个 onchange 事件很耗时

标签: delphi pascal editbox


【解决方案1】:

在表单上放置十个 TEdit 控件。由于您是手动创建的,因此您需要使它们在代码中易于访问,并且没有超级优雅的方法可以做到这一点。但这有效:

在您的实施部分,定义

type
  TEditorPair = record
    First,
    Second: TEdit;
  end;

并将私有字段FEditors: array[0..4] of TEditorPair; 添加到您的表单类。然后做

procedure TForm1.FormCreate(Sender: TObject);
begin
  FEditors[0].First := Edit1;
  FEditors[0].Second := Edit2;
  FEditors[1].First := Edit3;
  FEditors[1].Second := Edit4;
  FEditors[2].First := Edit5;
  FEditors[2].Second := Edit6;
  FEditors[3].First := Edit7;
  FEditors[3].Second := Edit8;
  FEditors[4].First := Edit9;
  FEditors[4].Second := Edit10;
end;

现在,选择所有 10 个编辑器控件,并向它们添加一个通用的 OnChange 事件。

procedure TForm1.EditorChange(Sender: TObject);

  procedure FailPair(PairIndex: integer);
  begin
    FEditors[PairIndex].First.Color := clRed;
    FEditors[PairIndex].Second.Color := clRed;
  end;

  procedure PassPair(PairIndex: integer);
  begin
    FEditors[PairIndex].First.Color := clWindow;
    FEditors[PairIndex].Second.Color := clWindow;
  end;

var
  i: Integer;
  n1, n2: integer;
begin
  for i := 0 to high(FEditors) do
  begin
    if (FEditors[i].First.Text = '') or (FEditors[i].Second.Text = '') then
      Continue;
    if TryStrToInt(FEditors[i].First.Text, n1) and TryStrToInt(FEditors[i].Second.Text, n2) then
      if InRange(n1+n2, 0, 3) then
        PassPair(i)
      else
        FailPair(i)
    else
      FailPair(i);
  end;
end;

Sample compiled EXE

如果你想打高尔夫球,EditorChange 过程可以缩短为

procedure TForm1.EditorChange(Sender: TObject);

  procedure PairFeedback(PairIndex: integer; Pass: boolean);
  const
    Colors: array[boolean] of TColor = (clRed, clWindow);
  begin
    FEditors[PairIndex].First.Color := Colors[Pass];
    FEditors[PairIndex].Second.Color := Colors[Pass];
  end;

var
  i: Integer;
  n1, n2: integer;
begin
  for i := 0 to high(FEditors) do
  begin
    if (FEditors[i].First.Text = '') or (FEditors[i].Second.Text = '') then
      Continue;
    PairFeedback(i, TryStrToInt(FEditors[i].First.Text, n1) and
      TryStrToInt(FEditors[i].Second.Text, n2) and InRange(n1+n2, 0, 3));
  end;
end;

我们使用了一些“技巧”,例如布尔短路(惰性)评估。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-23
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-12-31
    • 2020-04-05
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多