且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建控件数组?

更新时间:2023-12-06 11:50:04

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."