delphitopendialog

Delphi, openDialog, no window appears on click


I'm currently trying to slightly modify this tutorial on loading the Excel file into Delphi. I would like to use OpenDialog in order to get the file path and start subsequent procedures loading the file to the text box and launching the connecting procedures. I drafted the code below but noting happens after compiling the file and clicking on the button. My understanding is that clicking on the button should show the open file window. I do not understand why the window with the file selection is not coming up.

procedure TForm1.Button1Click(Sender: TObject);
var
  openDialog : TOpenDialog;    // Open dialog variable
  strConn : WideString; // Declare wide string for the connection

begin
  // Create the open dialog object - assign to our open dialog variable
  openDialog := TOpenDialog.Create(self);

  // Set up the starting directory to be the current one
  openDialog.InitialDir := GetCurrentDir;

  // Only allow existing files to be selected
  openDialog.Options := [ofFileMustExist];

  // Allow only .Excel and .pas files to be selected
  openDialog.Filter :=
    'Excel 2003|*.xls|Excel 2007 and newer|*.xlsx';

  // Select pascal files as the starting filter type
  openDialog.FilterIndex := 2;

  // Give file path to the edit
  Edit1.Text := openDialog.FileName;


  // Connect the Excel file
  AdoConnection1.Connected:=False;
  AdoConnection1.ConnectionString:=strConn;

  end;

Solution

  • You failed to show the dialog. Do it like this:

    if not openDialog.Execute then
      Abort;
    

    Obviously you need to do this after you've initialized the properties, but before you read the filename.

    You clearly have succeeded in doing this before, as can be seen from this earlier question. It would still, just as I said before, be a really good idea to keep the code to choose file names separate from the rest of your code. Try to arrange that sections of code perform one task, and one task alone. Doing so makes these sections of code composable.