Maybe you'll like better this other approach: Use the list box to keep the names and a synchronized array to keep the numbers; somewhat like the solution used in
this other postI've attached a small example program that demonstrates the use of this approach. The gist of it is in the methods
DoLoadFromFile(() and
DoSaveToFile.
The first loads the whole file in the listbox and then parses each item, converting the numeric part, storing it in a
separate array of integer and removing it (and the separator
' - ') from the listbox item.
To save to a file we simply walk through boh the listbox and the array at the same time, retrieving the literal part of from the listbox and the numeric part from the array, and converting them o a single line by using
Format(). This procedure uses a StringList for convenience but you could as well save the strings directly to a file.
Here is the relevant code for those who don't like to download attachments:
{ Fields in the form:
ListBox: TListBox;
FFileName: string;
FValues: array of Integer;
}
procedure TForm1.DoLoadFromFile(const Filename: String);
var
i, x: Integer;
aStr: String;
begin
if not FileExists(Filename) then
ShowMessageFmt(sInexistentFile, [ExtractFileName(Filename)])
else begin
ListBox.Items.LoadFromFile(Filename);
if ListBox.Count < 1 then
ShowMessageFmt(sEmptyFile, [ExtractFileName(Filename)])
else begin
SetLength(FValues, ListBox.Count);
for i := 0 to ListBox.Count-1 do begin
aStr := ListBox.Items[i];
x := Pos(' - ', aStr);
if x > 0 then begin
FValues[i] := StrToInt(Copy(aStr, x+3, Length(aStr)));
ListBox.Items[i] := Copy(aStr, 1, x-1);
end;
end; {for i := 0 to ListBox.Count-1}
FFileName := Filename;
end; {if ListBox.Count < 1 .. else}
end; {if not FileExists(Filename)...else}
end;
procedure TForm1.DoSaveToFile(const Filename: String);
var
AStrList: TStringList;
i: Integer;
begin
if ListBox.Count > 0 then begin
AStrList := TStringList.Create;
try
for i := 0 to ListBox.Count - 1 do
AStrList.Add(Format('%s - %d', [ListBox.Items[i], FValues[i]]));
AStrList.SaveToFile(FileName);
FFileName := Filename;
finally
AStrList.Free;
end;
end else
ShowMessageFmt(sInexistentFile, [FileName]);
end;