如此创建的动态控件数组,释放时怎么会出错?如果只创建一个动态控件,这样释放没问题

ahacrazydragon 2003-10-17 09:31:08
unit Unit1;

interface

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

type
TForm1 = class(TForm)
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);

private
{ Private declarations }
bAddLabel:array of TLabel;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);
var
iLoop :integer;
s :string[11];
begin
SetLength(bAddLabel,3);

for iLoop :=1 to 3 do
begin
bAddLabel[iLoop] := TLabel.Create(self);
Str(iLoop,s);
bAddLabel[iLoop].Parent := Form1;
bAddLabel[iLoop].Height := 60;
bAddLabel[iLoop].Width := 50;
bAddLabel[iLoop].Color := clBlue;
bAddLabel[iLoop].Caption := 'Dynamic create control' + ' ' + s + '个';
bAddLabel[iLoop].Top := Form1.Top + 40;
bAddLabel[iLoop].Left := form1.Left + 30 + (iLoop-1)*bAddLabel[iLoop].Width;
bAddLabel[iLoop].Show;
end
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
var
iLoop :integer;
begin
for iLoop :=1 to 3 do
begin
if bAddLabel[iLoop] <> nil then
bAddLabel[iLoop].free;
end;
bAddLabel := nil;
end;

end.
...全文
60 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
ahacrazydragon 2003-10-17
  • 打赏
  • 举报
回复
to XZHHAI(星之瀚海)

原来问题处在编号1上,动态控件的编号从0开始。已经给你结贴了,差点不知如何给分,呵呵,谢了
windindance 2003-10-17
  • 打赏
  • 举报
回复
for iLoop :=1 to 3 do
//下标从0开始!
reallike 2003-10-17
  • 打赏
  • 举报
回复
…… 不知道啥意思。
星之瀚海 2003-10-17
  • 打赏
  • 举报
回复
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
ArrLable: Array of TLabel;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.Button1Click(Sender: TObject);
var
I:Integer;
begin
SetLength(ArrLable,3);
For I:=0 to 2 do
begin
ArrLable[I] := TLabel.Create(self);
ArrLable[I].Caption := 'MyLabel'+IntToStr(i);
ArrLable[I].Parent := Self;
ArrLable[I].Visible := true;
ArrLable[I].Top := 50;
if I=0 then
ArrLable[I].Left := 40
else
ArrLable[I].Left := ArrLable[I-1].Left +100;
end;
update;
end;
上面是我写的测试,不用释放的,你试试
星之瀚海 2003-10-17
  • 打赏
  • 举报
回复
再有,数组的起始下标默认为0,而楼主是从1开始的
ahacrazydragon 2003-10-17
  • 打赏
  • 举报
回复
看不太懂你的意思?
你是说释放Form时不要对动态控件做任何事情?这样也不行的,一样的错误
星之瀚海 2003-10-17
  • 打赏
  • 举报
回复
如果是和窗体(self)一起释放,就不用显示释放,因为DElphi自己会帮你处理这些东西
ahacrazydragon 2003-10-17
  • 打赏
  • 举报
回复
不行,出现前面一样的错误,错误如下:
Project Project1.exe raised exception class EInvalidPointer with message 'Invalid pointer operation'. Process stopped. Use Step or Run to continue.
windindance 2003-10-17
  • 打赏
  • 举报
回复
for iLoop :=0 to High(bAddLabel) do
begin
bAddLabel[iLoop].free;
end;

SetLength( bAddLabel,0);

5,388

社区成员

发帖
与我相关
我的任务
社区描述
Delphi 开发及应用
社区管理员
  • VCL组件开发及应用社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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