I am using Delphi 2010 and I searched the internet and found a few examples, but neither of them worked. I am using it may because of 2010 and unicode? Anyway......
I am looking for two routines to do a simple save and load to and from file for a TListView. I am only interested in saving the string values in each column. i.e. the caption and the subitems. I am not interested in saving the layout or any objects.
procedure SaveToFile(const FileName: string);
procedure LoadFromFile(const FileName: string);
Here's something very crude. It uses a rather limited tab-delimited text format. The contents are not allowed to contain inline tab characters. I've also implemented no error checking whatsoever on the load function. I'm sure you can add that.
uses
ComCtrls, Types, StrUtils;
procedure ListViewSaveToFile(ListView: TListView; const FileName: string);
procedure AddTextToLine(var Line: string; const Text: string);
begin
Line := Line + Text + #9;
end;
procedure MoveCompletedLineToList(const Strings: TStringList; var Line: string);
begin
Strings.Add(System.Copy(Line, 1, Length(Line)-1));//remove trailing tab
Line := '';
end;
var
Strings: TStringList;
LatestLine: string;
i, j: Integer;
begin
LatestLine := '';
Strings := TStringList.Create;
try
for i := 0 to ListView.Items.Count-1 do begin
AddTextToLine(LatestLine, ListView.Items[i].Caption);
for j := 0 to ListView.Items[i].SubItems.Count-1 do begin
AddTextToLine(LatestLine, ListView.Items[i].SubItems[j]);
end;
MoveCompletedLineToList(Strings, LatestLine);
end;
Strings.SaveToFile(FileName, TEncoding.UTF8);
finally
Strings.Free;
end;
end;
procedure ListViewLoadFromFile(ListView: TListView; const FileName: string);
var
Strings: TStringList;
i, j: Integer;
Fields: TStringDynArray;
Item: TListItem;
begin
Strings := TStringList.Create;
try
Strings.LoadFromFile(FileName);
ListView.Clear;
for i := 0 to Strings.Count-1 do begin
Fields := SplitString(Strings[i], #9);
Item := ListView.Items.Add;
Item.Caption := Fields[0];
for j := 1 to high(Fields) do begin
Item.SubItems.Add(Fields[j]);
end;
end;
finally
Strings.Free;
end;
end;