I'm working with Delphi 7 and I'm trying to create a form programmatically. Here's my form class stub:
unit clsTStudentInfoForm;
interface
uses Forms;
type
TStudentInfoForm = class (TForm)
end;
implementation
end.
I also have a button on my main form (that's just a regular form that's supposed to create and show the form above at run-time) and when clicked it creates and shows the student form as a modal window. It does show the form but there's nothing on it. The only thing you can do is click the close button at the upper-right corner of the window to close it.
procedure TLibraryForm.btnShowStudentIfoFormClick(Sender: TObject);
var
f : TStudentInfoForm;
begin
f := TStudentInfoForm.CreateNew(Self);
f.ShowModal;
f.Free;
f := nil;
end;
I have no idea how to add components to a programmatically-created form (not at run-time, but to the source code). Can you help me write some code that adds an Okay button to the student form as well as sets the caption and the form's height and width (the code has to be written in the student form file)?
Any suggestions and examples will be highly appreciated. Thank you.
To add a form to your project, select either File > New > VCL Form or File > New > Multi-Device Form, according to the type of application you are creating.
Creating modal forms with controls on the fly is easy:
procedure CreateGreetingForm;
var
frm: TForm;
lbl: TLabel;
edt: TEdit;
btn: TButton;
begin
frm := TForm.Create(nil);
try
lbl := TLabel.Create(frm);
edt := TEdit.Create(frm);
btn := TButton.Create(frm);
frm.BorderStyle := bsDialog;
frm.Caption := 'Welcome';
frm.Width := 300;
frm.Position := poScreenCenter;
lbl.Parent := frm;
lbl.Top := 8;
lbl.Left := 8;
lbl.Caption := 'Please enter your name:';
edt.Parent := frm;
edt.Top := lbl.Top + lbl.Height + 8;
edt.Left := 8;
edt.Width := 200;
btn.Parent := frm;
btn.Caption := 'OK';
btn.Default := true;
btn.ModalResult := mrOk;
btn.Top := edt.Top + edt.Height + 8;
btn.Left := edt.Left + edt.Width - btn.Width;
frm.ClientHeight := btn.Top + btn.Height + 8;
frm.ClientWidth := edt.Left + edt.Width + 8;
if frm.ShowModal = mrOk then
ShowMessageFmt('Welcome, %s', [edt.Text]);
finally
frm.Free;
end;
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With