首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

怎样在程序中遍历某form有caption的控件,并将它们的caption加入到listbox1里面?解决方案

2012-03-07 
怎样在程序中遍历某form有caption的控件,并将它们的caption加入到listbox1里面?怎样在程序中遍历某form有c

怎样在程序中遍历某form有caption的控件,并将它们的caption加入到listbox1里面?
怎样在程序中遍历某form有caption的控件,并将这些有caption的控件的caption加入到listbox1里面?(这些控件包括有label、button、checkbox等等,不包括edit等)
procedure   TForm1.Button1Click(Sender:   TObject);
var
    i:   Integer;
begin
    for   i   :=   0   to   ComponentCount   -   1   do
    begin
        if   Components[i]   is   TLabel   then
            listbox1.Items.Add((Components[i]   as   TLabel).Caption);
        if   Components[i]   is   Tbutton   then
            listbox1.Items.Add((Components[i]   as   Tbutton).Caption);
    end;
end;
这段代码是分开一种一种的控件来添加,能否一次性添加,不用分哪种控件?

[解决办法]
implementation
uses TypInfo;
{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
propinfo: PPropInfo;
var
i: Integer;
begin
for i := 0 to ComponentCount - 1 do
begin
PropInfo := GetPropInfo(Components[i].ClassInfo, 'Caption ');
if propinfo <> nil then
listbox1.Items.Add(GetStrProp(Components[i], 'Caption '));
end;
end;

[解决办法]
Caption属性其实Control上就有了,就是protected而已。

type
TMyControl = class(TControl)
end;

procedure TForm1.Button1Click(Sender: TObject);
var
i: Integer;
begin
for i := 0 to ControlCount - 1 do
listbox1.Items.Add(TMyControl(Controls[i]).Caption);
end;

热点排行