R – Delphi – Creating controls before form Create is run

controlscreationdelphiforms

Well, my problem is as follows:

I have a Delphi 5 application that I'm essentially porting to Delphi 2010 (replacing old components with their latest versions, fixing the inevitable Ansi/Unicode string issues, etc.) and I've run into kind of a hitch.

Upon creation of one of our forms, an access violation happens. After looking it over, I've come to the conclusion that the reason for this is because one of the setters called in Create attempts to change a property of an object on the form that hasn't been created yet.

I've trimmed it down a little, but the code basically looks like this:

In form declaration:

property EnGrpSndOption:boolean read fEnGrpSndOption write SetGrpSndOption;

In form's Create:

EnGrpSndOption := false;

In Implementation:

procedure Myform.SetGrpSndOption(const Value: boolean);
begin
  fEnGrpSndOption := Value;
  btGrpSnd.Visible := Value;
end;

By tossing in a ShowMessage(BooltoStr(Assigned(btGrpSend), true)) right before btGrpSnd.Visible := Value, I confirmed that the problem is that btGrpSnd hasn't been created yet.

btGrpSend is an LMDButton, but I'm pretty sure that isn't quite relevant as it hasn't even been created yet.

While I realize I probably should only assign a value after confirming that the control is assigned, this would just result in the value set in create not being set to the actual control.

So what I want to do is find a way to make certain that all the controls on the form are created BEFORE my Create is run.

Any assistance in doing this, or information regarding how Delphi creates forms would be appreciated.
It worked back in Delphi 5, so I imagine the cause of this should be mentioned somewhere among the lists of changes between versions. Delphi 2010 is quite a bit newer than Delphi 5 after all.

Best Answer

Like Tobias mentioned (but advocates against) you can change the creation order (right at the form at change the creation order).

But you can also in the setter method check if the form is creating (csCreating in form.componentstate). And if it is you have to store that property value yourself, and handle it in AfterConstruction.

Related Topic