I have created a login form which holds buttons corresponding to users' names held in an Access file. The buttons are created in the OnCreate
event because I don't want to have to create them each time the screen is shown.
The buttons display as expected, and I have created LogOn and LogOff procedures, which both work as I expected.
The next step was to only display the buttons for users who are currently logged on to the system. To do this, I have created the following code in the OnActivate
event:
procedure TUserInForm.FormActivate(Sender: TObject);
var
btn : TLBButton;
begin
With UserQuery do begin;
first;
while (not eof) do begin
BtnName := FieldByName('UserName').AsString;
Btn := TLBButton(FindComponent(BtnName));
if (Btn <> nil) then
if (FieldByName('LoggedIn').AsBoolean = True) then Btn.Visible := True else Btn.Visible := False;
next;
end;
end;
end;
However, it doesn't find any of the buttons - they are all nil
. The code throws an Access Violation exception if I remove the nil
check. But, at no point in the code do I destroy the buttons or the form itself. The buttons exist, because I can see them on the form. The BtnName
variable is global within the unit. I've checked that the BtnName
variable is populated correctly from the table.
I've used code similar to this to find components before, with no problems. In fact, I "stole" the code shown above from another procedure (with the obvious changes) in which it works fine. The logs show no errors.
Can anyone suggest some approach to fixing this problem? It's very frustrating!
if X = True then
; simply writeif X then
. Hence,if (FieldByName('LoggedIn').AsBoolean = True) then Btn.Visible := True else Btn.Visible := False;
can be writtenif FieldByName('LoggedIn').AsBoolean then Btn.Visible := True else Btn.Visible := False;
. And, even more of an improvement:Btn.Visible := FieldByName('LoggedIn').AsBoolean
. Isn't that MUCH easier to read? – Andreas Rejbrand Jan 23 at 17:07FindComponent
is the wrong solution. And if you really must use it, you must also test its class before you use an unsafe cast (using theis
operator). – Andreas Rejbrand Jan 23 at 17:11begin
has a semicolon (and others don't). – AmigoJack Jan 23 at 17:30.Hint
and compare against that. – AmigoJack Jan 23 at 20:36