2
Answers

New to c# - how to create components, on the fly ??

Ask a question
Jan Lauenborg

Jan Lauenborg

17y
6.1k
1

Hi all, I am new to c#, comming from Delphi, I would like to ask if any of you guys out there can tell me how to create components on a form, on the fly.

I have some Delphi examples to show what I want c# to do.

First of all - creating a component on the fly, in the Delphi exampel I create a Panel and setup a few property, the most important is the component name, so I can find the component again when I want to change the property or free it. Also the parent and the owner is important to be able to display the component.

procedure TForm1.Button1Click(Sender: TObject);
begin
  With Tpanel.Create(Form1) do
  begin
    Parent:=Form1;
    Name:='Mypanel1';
    Caption:='My Cap';
    top:=20;
    Left:=20;
    Height:=100;
    Width:=100;
  end;
end;

The next problem is the way to find and use the component, the next to small procedures show what I mean..

The first one find component and use type cast to change the property..

procedure TForm1.Button2Click(Sender: TObject);
var
  P: TComponent;
begin
  P:=FindComponent('MyPanel1');
  if P<>nil then
  begin
    with TPanel(P) do
    begin
      top:=30;
      Left:=30;
      Height:=80;
      Width:=80;
      Caption:='New Cap';
    end;
  end;
end;

The last one does the same, but free the component from the memory..

procedure TForm1.Button3Click(Sender: TObject);
var
  P: TComponent;
begin
  P:=FindComponent('MyPanel1');
  if P<>nil then
  begin
    Tpanel(P).Free;
  end;
end;

It would make me very happy if some one could help me getting on with c#, thanks in advance.

Regards..

Jan

 


Answers (2)