Running into a runtime error when I open a modal form (Form2) that, on create, calls another procedure that does somehting with a VCL component. The following program demonstrates the issue.
This is the code on the modal form:
procedure DoLabel;
begin
form2.Label1.Caption := 'A';
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
DoLabel;
end;
This compiles well. However, the program crashes on opening the modal form. The debugger says: access violation at address xxxx. It is probably a basic error, but what am I doing wrong? And how to solve this?
You are using the global
Form2variable, which has not been assigned yet (or at all) while theTForm2object is still being constructed.You need to change your code to not rely on that variable during construction (and preferably remove it entirely, unless
TForm2is auto-created at startup, which it does not sound like it is).For instance, pass the Form's
Selfpointer, or even itsTLabelpointer, as an input parameter toDoLabel(), eg:Though, in this case, it would make more sense to have
DoFormStuff(), and possibleDoLabel()too, be a member of theTForm2class instead of free functions: