[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 292
  • Last Modified:

Create Open Dialog

When I try to create a TOpenDialog I get an EAccessViolation Error. Here is my code where the error occurs:

var
  OpenDlg: TOpenDialog;
  filename: string;

procedure TForm1.FormCreate(Sender: TObject);
begin
  OpenDlg.Create(OpenDlg); //Access Violation
  if OpenDlg.Execute then
  begin
    filename := OpenDlg.FileName;
  end;

Could anyone tell me how to fix this?
0
ding-dong
Asked:
ding-dong
  • 4
  • 3
1 Solution
 
MerijnBSr. Software EngineerCommented:
procedure TForm1.FormCreate(Sender: TObject);
begin
  OpenDlg := TOpenDialog.Create(OpenDlg); //Access Violation gone
  try
    if OpenDlg.Execute then
    begin
      filename := OpenDlg.FileName;
    end;
  finally
    OpenDlg.Free();
  end;
end;
0
 
JohnjcesCommented:
Try this...

procedure TForm1.Button1Click(Sender: TObject);
begin
  OpenDlg := TOpenDialog.Create(self); //Access Violation
  if OpenDlg.Execute then
  begin
    Edit1.Text := OpenDlg.FileName;
  end;  
end;

John
0
 
JohnjcesCommented:
Woops... remove the comment //Access violation as it is not there.

John
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
MerijnBSr. Software EngineerCommented:
always refresh before you post a comment :)
0
 
JohnjcesCommented:
MerijnB

WoopS! Alright I see the problem!!!! In just before me!

Sorry about that! I see that happen every so often... first time for me!

;-) John

0
 
Russell LibbySoftware Engineer, Advisory Commented:
The following code:

  OpenDlg:=TOpenDialog.Create(OpenDlg);

Is going to be prone to problems, and should not be used. If OpenDlg is not cleared (left pointing to an already freed object; aka stale pointer), then an access violation WILL occur. Not a problem for the first time use when the var is global in scope, but the second time is an issue. This is also an issue if the var is local in scope (not guaranteed to be nil). In short, poor practice.

If you don't need an owner then use var:=TOpenDialog.Create(nil), or as John pointed out, use Self, which in this case refers to the object who's method your calling (TForm1).

Russell


0
 
MerijnBSr. Software EngineerCommented:
oops, sorry, that was a very big typo, should of course be: OpenDlg := TOpenDialog.Create(self);
0
 
MerijnBSr. Software EngineerCommented:
(glad you are paying attention :))
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now