RAD Studio VCL Reference
ContentsIndex
PreviousUpNext
TOpenDialog Class

TOpenDialog displays a file-selection dialog.

Pascal
TOpenDialog = class(TCommonDialog);
C++
class TOpenDialog : public TCommonDialog;

TOpenDialog displays a modal Windows dialog box for selecting and opening files. The dialog does not appear at runtime until it is activated by a call to the Execute method. When the user clicks Open, the dialog closes and the selected file or files are stored in the Files property.  

Delphi Examples: 

 

{
This example uses a memo box, two buttons, an open dialog
and a save dialog on a form. When the application runs,
the open dialog and save dialog filters are initialized,
so to open and save *.txt files or files with any extension.
Clicking on the Open/Save button executes the open/save dialog.
An exception is raised when trying to open a file that
does not exist, or when trying to overwrite a file using the
save dialog.
}
procedure TForm1.Button1Click(Sender: TObject);
begin
  { execute an open file dialog }
  if OpenDialog1.Execute then
    { first check if file exists }
    if FileExists(OpenDialog1.FileName) then
      { if it exists, load the data into the memo box }
      Memo1.Lines.LoadFromFile(OpenDialog1.FileName)
    else
      { otherwise raise an exception }
      raise Exception.Create('File does not exist.');
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  { execute a save file dialog }
  if SaveDialog1.Execute then
    { first check if file exists }
    if FileExists(SaveDialog1.FileName) then
      { if it exists, raise an exception }
      raise Exception.Create('File already exists. Cannot overwrite.')
    else
      { otherwise, save the memo box lines into the file }
      Memo1.Lines.SaveToFile(SaveDialog1.FileName);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  {
  initialize the dialog filters to open/save *.txt files
  and also files with arbitrary extension
  }
  OpenDialog1.Filter := 'Text files (*.txt)|*.TXT|Any file (*.*)|*.*';
  SaveDialog1.Filter := 'Text files (*.txt)|*.TXT|Any file (*.*)|*.*';
end;

 

Copyright(C) 2009 Embarcadero Technologies, Inc. All Rights Reserved.
What do you think about this topic? Send feedback!