Delphi – Filtering open dialog according pre-defined filename

delphifileopendialogfilter

  1. Question number 1:
    I want to filter open dialog that will only display certain file name. The file name is given on TEdit box. This is my code, but it still show the whole file in the directory.

    procedure TForm1.ButtonLoad(Sender: TObject);

    var
      openDialog: TOpenDialog; 
      i: Integer;
    begin
     TFBusy(sender);
      openDialog := TOpenDialog.Create(self);
      openDialog.Title := 'Browsing desired file, Browse for '+ TEdit1.Text;
      openDialog.InitialDir := strMyDoc;
      openDialog.FileName := TEdit1.Text;
      openDialog.Filter := 'All file extension|*.*';
      try
        if not openDialog.Execute then
        begin
    mem0.lines.add('Browse file to load was cancelled');
        end;
      finally
    
      for i := 0 to openDialog.Files.Count - 1 do
          //i do here with the file
    
      end;
      openDialog.Free;
      TFReady(sender);
    end;
    

Although the file name on open dialog display correctly, but it's still displays the whole files inside directory.

Question number 2:

Can I filter file with certain prefix?
E.g; My file name is FLOWER-3320, FLOWER-2230, and so on. SO i want to filter open dialog that will only display any file with prefix name FLOWER- (ignore file extension)

Best Wishes,
Bee.

Best Answer

It shows all files because you explicitly told it so:

openDialog.Filter := 'All file extension|*.*';

Setting the filename alone does not filter the open dialog.

You can use a filter like this:

openDialog.Filter := 'Flower Files|FLOWER-*.*';

to display all files with prefix "FLOWER-". If you want to filter all but one specific filename, just leave out the wildcard in the first part of the filter:

openDialog.Filter := 'Flower-2230 File|FLOWER-2230.*';

But (as David points out in his comment) why have an open dialog when you restrict the selection to a single file?

Related Topic