简体   繁体   中英

Delphi - AV error when using second form

I have a main form which uses the following code to create a sub-form, when a button is clicked. The form to be created ( frmNewMember ) has been removed from the auto-create forms list.

procedure TfrmMain.btnAddMemberClick(Sender: TObject);
var
  NewMemberForm: TForm;
begin
  NewMemberForm := TfrmNewMember.Create(Application);
  try
    NewMemberForm.ShowModal;
  finally
    NewMemberForm.Free;
  end;
end; 

The AV occurs when I try to use a component within a procedure which I have created within the form. For example:

procedure DoSomething;
begin
  frmNewMember.edtPostcode.Text := 'TEST';
end;

This would raise an AV with read error 000003BC. Is this occurring because I am trying to access an instance of frmNewMember which doesn't exist? I'm sure there's a simple answer to this, but I've searched all over the place and can't seem to get rid of the AV error.

This is your problem:

frmNewMember

This is the global variable that the Delphi IDE (un)helpfully declared for you. You've never assigned it, and so it is still nil. Hence the access violation.

You've stopped using auto-create which is the right thing to do. The next step is to purge your code of these useless global variables. Once you've done that you cannot make this mistake again.

You'll still need to get the form reference into that function. But now you can pass it in as a parameter. Or make the function be a method of the form. That makes your code better too, so you keep on winning.

I think of this issue as the curse of VB . The global form variable was added to allow Delphi to mimic the behaviour of VB. We long since realised that VB sucked in that regard. But we are still left with these dreadful globals.


Asides:

  • The local variable may as well be declared as TfrmNewMember.
  • There is no point passing Application to the constructor since you manage the life with a try/finally. Pass nil instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM