Passing file path in Delphi from TOpenDialog as a string -


i'm trying make use of topendialog in order pass path selected file adoconection , load content of excel file table. i'm attempting code below last part of code not connect excel returning error: [dcc32 error] sample_map.pas(80): e2010 incompatible types: 'string' , 'topendialog'

procedure tform1.button1click(sender: tobject); var   opendialog : topendialog;    // open dialog variable   strconn : widestring; // declare wide string connection  begin   // create open dialog object - assign our open dialog variable   opendialog := topendialog.create(self);    // set starting directory current 1   opendialog.initialdir := getcurrentdir;    // allow existing files selected   opendialog.options := [offilemustexist];    // allow .dpr , .pas files selected   opendialog.filter :=     'excel 2003 , older|*.xls|excel 2007 , older|*.xlsx';    // select pascal files starting filter type   opendialog.filterindex := 2;    // display open file dialog   if opendialog.execute   showmessage('file : '+opendialog.filename)   else showmessage('open file cancelled');    // free dialog   opendialog.free;    // connect excel file     strconn:='provider=microsoft.jet.oledb.4.0;' +                  'data source=' + opendialog + ';' +                  'extended properties=excel 8.0;';         adoconnection1.connected:=false;         adoconnection1.connectionstring:=strconn; end; 

opendialog instance of file dialog. not string. need read filename property of file dialog object this:

opendialog.filename 

in fact use in 1 of showmessage calls.

do make sure read property before calling free, mistake present in code in question.

in fact need in habit of using try/finally protect resources. time create instance of class need make sure destroyed in face of exception. in code need write this:

opendialog := topendialog.create(self); try   .... // use opendialog let user choose file:   strconn := 'provider=microsoft.jet.oledb.4.0;' +              'data source=' + opendialog.filename + ';' +              'extended properties=excel 8.0;';   opendialog.free; // executes no matter what, if exception raised, etc. end; 

i don't think need use widestring here. if use unicode delphi can use native string type alias unicodestring. if delphi pre-unicode, can safely use string, alias ansistring in case. literals use ascii. file dialog ansi control , opendialog.filename ansi. nothing gained using widestring.

finally, mixing up, in 1 function, code select filename, , code work on database connection. better separate concerns. create method returns filename, obtained letting user choose through dialog. , add method work on database connection, passed filename parameter.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -