动态创建控件 list index out of bounds

QNE1410 2012-03-29 05:05:12
运行时点击按钮出现list index out of bounds(3),之后是list index out of bounds(2),再按则正常,什么问题呢?



unit Unit1;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ComCtrls;

type
TControlClass=class of TControl;
TForm1 = class(TForm)
MonthCalendar1: TMonthCalendar;
Memo1: TMemo;
ColorBox1: TColorBox;
RadioGroup1: TRadioGroup;
Button1: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
procedure createControlObj(ControlClass:TControlClass);
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.createControlObj(ControlClass:TControlClass);
var AControlObj:TControl;
begin
AControlObj:=ControlClass.Create(self);//根据不同的类类型,动态创建对象
AControlObj.Parent:=self;//指定TForm1为控件的容器
AControlObj.Name:=AControlObj.ClassName;//以类名作为控件名
AControlObj.SetBounds(10,10,250,150);//设置控件边界
Label1.Caption:=AControlObj.ClassName;
end;

procedure TForm1.Button1Click(Sender: TObject);
const
//定义一个以控件类类型为元素的数组
ContrlClassArry:array[0..2] of
TControlClass=(TMonthCalendar,TMemo,TColorBox);
var
i:Integer;
begin
//清空已经动态生成的控件
for i := 0 to controlcount-1 do
if (Controls[i] is TMonthCalendar) or (Controls[i] is TMemo)
or (Controls[i] is TColorBox) then
Controls[i].Free;
//调用构造函数,动态生成用户选定的控件
createControlObj(ContrlClassArry[RadioGroup1.ItemIndex]);
end;

end.
...全文
197 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
QNE1410 2012-03-29
  • 打赏
  • 举报
回复
十分感谢各位
结贴
山东蓝鸟贵薪 2012-03-29
  • 打赏
  • 举报
回复
问题是越界了,可能那个地方设置不对
我看见佛 2012-03-29
  • 打赏
  • 举报
回复
我来解释下吧:你释放一个控件后,controlcount的值同时也改变了,而此时i的值在增加,而controlcount的值在减少





ccrun.com 2012-03-29
  • 打赏
  • 举报
回复
因为每删除一个对象,ControlCount就会发生变化。所以,要从大到小的删除。
QNE1410 2012-03-29
  • 打赏
  • 举报
回复
O(∩_∩)O哈,行了,非常感谢。
不过这是什么意思呢?
可否解释一下
kaikai_kk 2012-03-29
  • 打赏
  • 举报
回复
for i := 0 to controlcount-1 do
==>
for i := controlcount-1 downto 0 do

16,749

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 语言基础/算法/系统设计
社区管理员
  • 语言基础/算法/系统设计社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧