Author: Jonas Bilinkevicius
How can I open a file and add lines which start with PIL to a listbox. When I
delete the appropriate line in the listbox, the line in the file should also be
deleted.
Answer:
Load the complete file into a TStringList instance. Then iterate over the Items in
the list and use the Pos function to check if the line starts with PIL, if it does
you add it to the listbox. When time comes to save the possibly changed file back
you again walk over the items in the listbox, but this times you do it from last to
first. For each line that starts with PIL you use the listbox.items.indexof method
to see if it is in the listbox, if not you delete it from the stringlist. Then you
write the stringlist back to file. Example:
In the forms private section you declare a field
1 2 FFilelines: TStringList;
3 4 //In the forms OnCreate event you create this list:5 6 FFilelines := TStringList.Create;
7 8 //In the forms OnDestroy event you destroy the list:9 10 FFilelines.Free;
On file load you do this:
11 12 FFilelines.Loadfromfile(filename);
13 listbox1.items.beginupdate;
14 try15 listbox1.clear;
16 for i := 0 to FFilelines.count - 1 do17 if Pos('PIL', FFilelines[i]) = 1 then18 listbox1.items.add(FFilelines[i]);
19 finally20 listbox1.items.endupdate;
21 end;
22 23 //To save the file you do this:24 25 for i := FFilelines.count - 1 downto 0 do26 if Pos('PIL', FFilelines[i]) = 1 then27 if listbox1.items.indexof(FFilelines[i]) < 0 then28 FFilelines.Delete(i);
29 FFilelines.SaveToFile(filename);