Ort*_*x92 2 delphi pascal editbox
我正在做一个学校项目,我有10个文本框(5对).
这个想法是每对的总和最多可以是"3".所以
[1] [2]
[1] [0]
...
[2] [1]
我认为在"onChange"事件中检查这个太耗时了,所以我决定用一个检查所有这些的按钮.只要任何一对不满足要求,它就会抛出一个showmessage().
现在有办法检查每一对并检查它们的值是否小于或等于三并且不是负数?我知道我可以通过编写大量代码手动完成,但我希望尽可能保持干净.
谢谢!
删除TEdit表单上的十个控件.由于您已手动创建这些,因此您需要在代码中轻松访问它们,并且没有超级优雅的方法来执行此操作.但这有效:
在您的实现部分中,定义
type
TEditorPair = record
First,
Second: TEdit;
end;
Run Code Online (Sandbox Code Playgroud)
并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;
Run Code Online (Sandbox Code Playgroud)
现在,选择所有十个编辑器控件,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;
Run Code Online (Sandbox Code Playgroud)
如果您要打高尔夫球,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;
Run Code Online (Sandbox Code Playgroud)
我们利用一些"技巧",例如布尔短路(懒惰)评估.
| 归档时间: |
|
| 查看次数: |
781 次 |
| 最近记录: |