在动态给combobox赋值时出错。
请各位指教。谢谢。
For i:=2 to 21 Do
  Begin
    With TCombobox(FindComponent('combobox'+Inttostr(i))) Do
    Begin
      Items.Clear;
    End;
  End;
  With QAddMt Do
  Begin
    Close;
    Sql.Clear;
    Sql.Add('Select * from Material');
    Open;
    SNo:=FieldByName('Mt_No').AsString;
    While Not Eof Do
    Begin
      For j:=2 To 21 Do
      Begin
        With TCombobox(FindComponent('combobox'+InttoStr(i))) Do
        Begin
          Items.Add(SNo);//循环取出值给SNo,此句报错
        End;
      End;
      Next;
    End;
  End;

解决方案 »

  1.   

    FindComponent('combobox'+InttoStr(i))先判斷FindComponent的返回值是否為nil
      

  2.   

    For i:=2 to 21 Do
      Begin
        With TCombobox(Self.FindComponent('combobox'+Inttostr(i))) Do  //加Self 即父名
        Begin
          Items.Clear;
        End;
      End;
      With QAddMt Do
      Begin
        Close;
        Sql.Clear;
        Sql.Add('Select * from Material');
        Open;
        SNo:=FieldByName('Mt_No').AsString;
        While Not Eof Do
        Begin
          For j:=2 To 21 Do
          Begin
            With TCombobox(Self.FindComponent('combobox'+InttoStr(i))) Do  //加Self,即父名
            Begin
              Items.Add(SNo);//循环取出值给SNo,此句报错
            End;
          End;
          Next;
        End;
      End;
      

  3.   

    //我全部把你重新写过了, 这样写OK的 
    //可以把 0 to ComponentCount-1  改成你想要了,我是遍历窗体所有组件
    procedure TForm1.btn1Click(Sender: TObject);
    var
      //QAddMT:TAdoQuery;
      Comp:TComponent;
      I, J:Integer;
      SNO:string;
    begin
      Comp:=nil;
      for I:=0 to ComponentCount-1 do begin
        Comp:=FindComponent('Combobox'+inttostr(I));
        if (Comp<>nil) and (Comp is TComboBox) then begin
          With Comp As TComboBox Do Begin
            Items.Clear;
          End;
        end;
        With QAddMt Do Begin
          Close;
          Sql.Clear;
          Sql.Add('Select * from Material');
          Open;
          SNo:=FieldByName('Mt_No').AsString;
          While Not Eof Do Begin
            For j:=0 to ComponentCount-1 Do begin
              Comp:=nil;
              if (Comp<>nil) and (Comp is TComboBox) then begin
                With Comp As TComboBox Do begin
                  Items.Add(SNo);
                End;
              end;
            End;
            Next;
          End;
        End;
      end;
    end;end.
      

  4.   

    可能是没有找到你想要的Combobox