Thursday, December 8, 2011

How to load data from a memo to a string grid?

I've used a memo to save data into a file, I've used this code:





Memo1.Lines.SavetoFile(filename.dat);





Is it possible for me to load this data into a string grid, if so, how?


I'm using Delphi btw.|||Hi there,



While it depends on where you plan to load the data from and how you have the data delimited, this is pretty easy to do in Delphi. If you want to load the data from the file, you would need something like the following listing:- (If you plan to load the data from the memo directly, it will be roughly the same, but with a different data source.)



If you want the full demo project, mail me (mystic.smeg@yahoo.co.uk) and I'll archive it up and send it to you.



na



---- listing ----



type TValues = array of string;



{... code ...}



function SplitStr(aData: string; aDelimiter, aQuoteChar: Char; TrimStr: Boolean): TValues;

var buf: string;

b: Boolean;

l,i,n: Integer;

begin

//convert a delimited string into an array of strings

i:=1; n:=0; b:=False;

SetLength(Result,n);

aData:=aData+aDelimiter;

l:=Length(aData);

while i%26lt;=l do

begin

if (aQuoteChar%26lt;%26gt;#0) and (aData[i]=aQuoteChar) then

b:=not(b)

else

if (aData[i]=aDelimiter) and not(b) then

begin

if TrimStr then buf:=Trim(buf);

Inc(n); SetLength(Result,n);

Result[n-1]:=buf; buf:='';

end else

buf:=buf+aData[i];

inc(i);

end; //while

end; {SplitStr}



{... code ...}



procedure TForm1.Button1Click(Sender: TObject);

var f: TextFile;

v: TValues;

s: string;

i,r: integer;

begin

//populate a stringgird from delimited file

if OpenDialog1.Execute then

try

StringGrid1.FixedCols:=0;

StringGrid1.FixedRows:=0;

StringGrid1.ColCount:=1;

AssignFile(f,OpenDialog1.FileName);

Reset(f); r:=1;

While not(EOF(f)) do

try

ReadLn(f,s);

v:=SplitStr(s,',','"',True);

StringGrid1.RowCount:=r;

if StringGrid1.ColCount%26lt;High(v) then

StringGrid1.ColCount:=High(v)+1;

for i:=0 to High(v) do

StringGrid1.Cells[i,r-1]:=v[i];

Inc(r);

except

on e: Exception do

raise e;

end; //try

finally

CloseFile(f);

end; //try

end;



{... code ...}

No comments:

Post a Comment