为什么这段代码按了按钮后没有反应?如果删掉Panel2就能显示Components[I].Name
procedure TForm1.Button1Click(Sender: TObject);
var
  I:Integer;
begin
 for I:=0 to Panel2.ComponentCount-1 do
  begin
    if (Panel2.Components[I] is TComboBox) then
      begin
        if ((Panel2.Components[I] as TComboBox).Text='')  then
        ShowMessage(Panel2.Components[I].Name);
      end;
  end;
end;

解决方案 »

  1.   

    你单步调试一下就会发现Panel2.ComponentCount=0
    把Panel2改成self就可以了,其余的代码没问题
      

  2.   

    for I:=0 to Panel2.ComponentCount-1 do

    Panel2改为Self
      

  3.   

    还是不行啊。
    在Form1上有Panel1,在Panel1上有PageControl1和Panel2,Button1在Form1上,PageControl1和Panel2上都有ComboBox,我只想要得到Panel2上的ComboBox是不是为空,要是代码改为下面的,点击按钮就出错(List index out of bounds"0")。
    procedure TForm1.Button1Click(Sender: TObject);
    var
      I:Integer;
    begin
     for I:=0 to Self.ComponentCount-1 do
      begin
        if (Panel2.Components[I] is TComboBox) then
          begin
            if ((Panel2.Components[I] as TComboBox).Text='')  then
              ShowMessage(Panel2.Components[I].Name);
          end;
      end;
    end;
    如果把所有的Panel2都改为Self,点击按钮后会把PageControl1上的ComboBox也计算在内。
    我已把代码中的Text改为Left(代码如下),问题可以解决,但不知有没有用只查找Panel2中的ComboBox和Text=''的方法来实现的代码,且当有两个以上的ComboBox的Text为空时,只显示一次对话框就把所有的ComboBox的名称全部显示出来?因为当两个ComboBox是在垂直方向左对齐的时候,在Panel2中和不在Panel2中的ComboBox其Left是不一样的,下面的代码会把不在Panel2中的Left大于80的ComboBox也计算在内。请赐教。以下是我改后的新代码:
    procedure TForm1.Button1Click(Sender: TObject);
    var
      I:Integer;
    begin
     for I:=0 to Self.ComponentCount-1 do
      begin
        if (Components[I] is TComboBox) then
          begin
            if ((Components[I] as TComboBox).Left >80 )  then
              ShowMessage(Components[I].Name);
          end;
      end;
    end;
    还有一个问题:在Panel2上明明有好几个ComboBox,为什么Panel2.ComponentCount=0?