如何创建控件数组? [英] How to create an array of controls?

查看:410
本文介绍了如何创建控件数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须创建一个数组并将所有控件放置在其中才能访问它们。这是一个简短的示例:

I have to create an array and place all controls there in order to access them.Here's a short example:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    Button3: TButton;
    const Test:Array[0..2] of TButton = (Button1,Button2,Button3);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

end.

在声明数组的那一行中未声明的标识符 Button1,但是在上面三行声明了它。

Undeclarated idenitifier 'Button1' at the line where I declarated my array.But it's declarated three lines above.

问题出在哪里,如何将所有控件放入数组中?

Where's the problem,how to put all controls in an array?

编辑:

谢谢您的回答,但我遇到了问题:

Thank you for your answers,but I've got problems:

 var TestA:TObjectList<TButton>;

 var index:TComponent;
 begin
 TestA := TObjectList<TButton>.Create(false);
   for index in Form7 do
     if pos(index.name, 'Button') = 1 then
       TestA.add(TButton(index));

 TestA[0].Caption := 'Test'; //Exception out of range.


推荐答案

Ben的权利。您无法在表单设计器中设置控件数组。但是,如果您有110张图像,对于这种特定情况,您可以将它们放入TImageList组件中,并将其图像集合视为一个数组。

Ben's right. You can't set up a control array in the form designer. But if you have 110 images, for this specific case you can put them into a TImageList component and treat its collection of images as an array.

如果您有一个一堆更多的普通控件(例如按钮),则必须创建一个数组并将其加载到代码中。有两种方法可以做到这一点。 Ben的答案是最简单的方法,至少对于小阵列而言。对于大型控件集或经常更改的控件集(例如,设计尚未完成的控件集),只要确保为它们赋予所有序列名(Button1,Button2,Button3 ...),就可以尝试一下像这样:

If you've got a bunch of more normal controls, like buttons, you'll have to create an array and load them into it in code. There are two ways to do this. The simple way, for small arrays at least, is Ben's answer. For large control sets, or ones that change frequently, (where your design is not finished, for example,) as long as you make sure to give them all serial names (Button1, Button2, Button3...), you can try something like this:

var
  index: TComponent;
  list: TObjectList;
begin
  list := TObjectList.Create(false); //DO NOT take ownership
  for index in frmMyForm do
    if pos('Button', index.name) = 1 then
      list.add(index);
   //do more stuff once the list is built
end; 

(使用 TObjectList< TComponent> ,或什至更具体的东西,如果您使用的是D2009。)根据上面的代码构建列表,然后编写一个排序函数回调,该回调将根据名称对它们进行排序,并使用它对列表进行排序,您已经获得了您的数组。

(Use a TObjectList<TComponent>, or something even more specific, if you're using D2009.) Build the list, based on the code above, then write a sorting function callback that will sort them based on name and use it to sort the list, and you've got your "array."

这篇关于如何创建控件数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆