1

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;
Konrad
  • 17,740
  • 16
  • 106
  • 167
  • 1
    How is this not covered in your [previous question](http://stackoverflow.com/questions/24447235/passing-file-path-in-delphi-from-topendialog-as-a-string) (and both of the answers you received to it)? It helps when following tutorials if you do more than just copy and paste code, and instead actually *read* and try to understand the code and what it's doing. – Ken White Jul 03 '14 at 14:08
  • I think you need to step back a bit and take time to try to understand the code rather than just paste it into the editor and run it. – David Heffernan Jul 03 '14 at 14:09
  • 2
    You should also free the dialog when you are done with it (or, possibly, reuse a single dialog). – Andreas Rejbrand Jul 03 '14 at 14:23

1 Answers1

2

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.

Community
  • 1
  • 1
David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490