请看代码:
var
a:TCheckbox; for i:=0 to j-1 do
  begin
    a:=Tcheckbox.create(nil);
    a.Caption:=k[i];
    a.Name:='NO'+inttostr(i);
    a.Left:=5;
    if i=0 then
    a.Top:=5
    else
    a.Top:=i*17+5 ;
    panel1.InsertControl(a);
end;我想实现:根据窗体中button的个数控制产生Checkbox的个数,并把button中的caption中内容赋值到checkbox.caption中

解决方案 »

  1.   

    帮助里说的很清楚:
    This example uses a button placed next to a group box. When the user clicks the button, the group box becomes the parent of the button, so the button moves inside the group box.procedure TForm1.Button1Click(Sender: TObject);begin
      RemoveControl(Button1);
      GroupBox1.InsertControl(Button1);end;Note that it was necessary to remove the button from the Controls property of the form before the button actually moves into the group box.This code accomplishes the same thing:procedure TForm1.Button1Click(Sender: TObject);begin
    Button1.Parent := GroupBox1;end;
    //////////////////////////////////
    在insertcontrol之前要先removecontrol
    或者干脆就使用parent
      

  2.   

    将Tcheckbox.create(nil)中的nil改为panel1,即可。
      

  3.   

    一个例子(在Form1上放置一个Button1,一个Panel1):procedure TForm1.Button1Click(Sender: TObject);var
        i,ileft,j : integer;
         Myckbox:TCheckbox;
    begin
        ileft:=0;
        for i:=1 to 4 do
        begin
          myckbox := TCheckbox.Create(Self);
          myckbox.Left :=ileft;
          Myckbox.Top := 20;
          Myckbox.Parent :=Panel1;
          Myckbox.Name := 'myckbox'+intTostr(i);
          Myckbox.Caption:=myCkbox.Name;
          inc(ileft,100);
        end;
        for j:= 0 to panel1.ControlCount - 1 do begin
               if panel1.Controls[j] is TCheckbox then
                        ShowMessage(panel1.Controls[j].Name);
         end;
    end;
      

  4.   

    出现新问题if panel1.ControlCount>0 then
     for i:=0 to panel1.ControlCount-1 do
        panel1.Controls[i].Destroy;Panel1.ControlCount=11
    但循环到i=6时发生 list indexs out in bounds错误
    现在还找出原因所在
      

  5.   

    这是因为,如果按照wzrlover(流光逝水) 的例子,建出来的combox的编号,与名称不一致,例子的是 control[0]  -〉 myckbox1  
    把你出现新问题的代码改为
    i:=0;
    if panel1.ControlCount>0 then
     while i<=panel1.ControlCount-1 do
      if panel1.Controls[i] is TCheckbox then
      begin
        ShowMessage(panel1.Controls[i].Name);
        panel1.Controls[i].Destroy;
      end;
    end;
      

  6.   

    此外,按照你的代码,在destroy myckbox1后,系统认为panel上的第0个控件是myckbox2,第1个控件是myckbox3,此时,你的i 已经是1 了,所以程序destroy myckbox3;之后,系统认为panel上的第0个控件是myckbox2,第1个控件是myckbox4,此时,你的i 已经是2 了,可是这时有可能没有再下一个控件了(如共建立4个)。
      

  7.   

    澄清一点:
             Controls是相对共同Parent
             Components是相对共同Owner
    ////////
    for i=panel1.Controls[i]-1 down to 0 do
    .........