我在form1的onshow中在scrollbox中动态定义了2个CheckBox,如下:
var
arraycb1:array of TCheckBox;
i:integer;
begin
SetLength(arraycb1,2);
for i:=0 to 1 do
begin
arraycb1[i]:=Tcheckbox.Create(scrollbox);
arraycb1[i].Parent:=self.scrollbox;
arraycb1[i].Left :=10;
arraycb1[i].top:=10+i*20;
arraycb1[i].Caption :=cb+inttostr(i);
arraycb1[i].show;
arraycb1[i]:=nil;
end;
end;
现在我想显示scrollbox中的2个Checkbox中选中(checked)的Checkbox的caption.
在button单击事件中:
var
i:integer;
strRelut:string;
begin
i:=0;
while i< scrollbox.ControlCount do
begin
if (self.ScrollBox.controls[i] is TCheckBox) then
begin
if (TCheckBox(ScrollBox.Controls[i]).checked) then
strRelut:=TCheckBox(self.ScrollBox.Controls[i]).Caption + +strRelut;
end;
i:=i+1;
end;
end;
但奇怪的是:当2个checkbox都未checked时,scrollbox.ControlCount为2,有一个checked时却为4,strrelut为‘cb0 cb0而不为’cb0,我该怎样改呀?
我怎样才能得到scrollbox中的2个Checkbox中选中(checked)的Checkbox的caption??
你把onshow的写在一个button的click你就知道什么原因了,
因为你的调试的时候转到了delphi中,
而第二次在看界面时,又运行了一次onshow,这时候scrollbox中的就变四个了,
你在跟踪下一次就是6个,和选择不选择没有关系的。
我刚试过了,把 onshow的写在一个button的click ,没有任何问题。
看你贴出的代码好像没什么错啊!
建议你在
if (TCheckBox(ScrollBox.Controls[i]).checked) then
strRelut:=TCheckBox(self.ScrollBox.Controls[i]).Caption + +strRelut;
showmessage(strRelut+inttostr(i));//加上这句,调试看看!
end;
i:=i+1;
什么问题,
我这里试了,没有问题呀。
这是我试验的源吗
建一个工程,主表单上两个button和一个scrollbox
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
ScrollBox: TScrollBox;
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
arraycb1:array of TCheckBox;
i:integer;
begin
SetLength(arraycb1,2);
for i:=0 to 1 do
begin
arraycb1[i]:=Tcheckbox.Create(scrollbox);
arraycb1[i].Parent:=self.scrollbox;
arraycb1[i].Left :=10;
arraycb1[i].top:=10+i*20;
arraycb1[i].Caption :=cb+inttostr(i);
arraycb1[i].show;
arraycb1[i]:=nil;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
i:integer;
strRelut:string;
begin
i:=0;
while i< scrollbox.ControlCount do
begin
if (self.ScrollBox.controls[i] is TCheckBox) then
begin
if (TCheckBox(ScrollBox.Controls[i]).checked) then
strRelut:=TCheckBox(self.ScrollBox.Controls[i]).Caption + +strRelut;
end;
i:=i+1;
end;
showmessage(strrelut);
end;
end.
你试试
按照楼上的代码是可行的。
你重新建立新专案后应该行。
你可以判断一下
var
arraycb1:array of TCheckBox;
i:integer;
begin
if scrollbox.ControlCount<2 then//如果已经创建就不要在创建
begin
SetLength(arraycb1,2);
for i:=0 to 1 do
begin
arraycb1[i]:=Tcheckbox.Create(scrollbox);
arraycb1[i].Parent:=self.scrollbox;
arraycb1[i].Left :=10;
arraycb1[i].top:=10+i*20;
arraycb1[i].Caption :=cb+inttostr(i);
arraycb1[i].show;
arraycb1[i]:=nil;
end;
end;
end;