Delphi初学者 - 使用TEdit循环

时间:2015-11-05 17:56:10

标签: image delphi loops edit

我有10个TEdits和10个图像,我试图使用它:

procedure TForm1.Button1Click(Sender: TObject; edit: TEdit);
var i:integer;
begin
for i:= 1 to 10 do
  begin
   if edit[i].text:='1' then picture[i].Show else picture[i].Hide;
  end;
end;

但delphi返回此错误:[错误] Unit1.pas(84):类没有默认属性

我也试过这个:

procedure TForm1.Button1Click(Sender: TObject);
var i:integer;
begin
for i:= 1 to 10 do
  begin
   if edit[i].text:='1' then picture[i].Show else picture[i].Hide;
  end;
end;

但是,再次,Delphi返回错误:

  

[错误] Unit1.pas(84):未声明的标识符:'edit'。

你能帮我解决一下这段代码吗?

2 个答案:

答案 0 :(得分:4)

您需要声明并填充自己的数组,然后您可以在需要时循环遍历它们,例如:

type
  TForm1 = class(TForm)
    Button1: TButton;
    ...
    Edit1: TEdit;
    Edit2: TEdit;
    Edit3: TEdit;
    // and so on ...
    Image1: TImage;
    Image2: TImage;
    Image3: TImage;
    // and so on ...
    procedure FormCreate(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    ...
  private
    edit: array[1..10] of TEdit;
    picture: array[1..10] of TImage;
    ...
  end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  edit[1] := Edit1;
  edit[2] := Edit2;
  edit[3] := Edit3;
  // and so on...
  picture[1] := Image1;
  picture[2] := Image2;
  picture[3] := Image3;
  // and so on...

  {
  alternatively:

  for I := 1 to 10 do
  begin
    edit[i] := TEdit(FindComponent('Edit' + IntToStr(i)));
    picture[i] := TImage(FindComponent('Image' + IntToStr(i)));
  end;
  }
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  I: integer;
begin
  for I := 1 to 10 do
  begin
   if edit[i].Text = '1' then
     picture[i].Show
   else
     picture[i].Hide;
   {
   alternatively:
   picture[i].Visible := (edit[i].Text = '1');
   }
  end;
end;

答案 1 :(得分:4)

你可以做以下两件事之一:

  1. 使用表单的Components列表和FindComponent

    procedure TForm1.Button1Click(Sender: TObject);
    var 
      i: Integer;
      TempEdit: TEdit;
    begin
      for i:= 1 to 10 do
      begin
        TempEdit := Self.FindComponent('Edit' + IntToStr[i]) as TEdit;
        if Assigned(TempEdit) then
        begin
          if TempEdit.Text = '1' then
            Picture[i].Show
          else
            Picture[i].Hide;
        end;
      end;
    end;
    
  2. 维护一个单独的TEdit控件数组,并直接引用它们。分配Picture[i]后,将匹配的TEdit添加到Edits[i],然后

    procedure TForm1.Button1Click(Sender: TObject);
    var 
      i: Integer;
    begin
      for i:= 1 to 10 do
      begin
        if Edits[i].Text = '1' then
            Picture[i].Show
          else
            Picture[i].Hide;
        end;
      end;
    end;