Re: Detecting if changes have been made
Posted by webmaster Guido on August 22, 2002 at 05:35:19:
In Reply to: Detecting if changes have been made posted by P12256 + Lesley on August 21, 2002 at 06:41:12:
: 1. Where a file has been opened and the user clicks on File Save - how can I get it to save to the file without displaying the File Save As Dialog box yet ask for a filename when the file is new?
: 2. Detect if the contents of a list box have changed or had new entries added to it and if true, then ask the user if they want to save the changes when they select File Exit
1A. Declare a global string variable that contains the filename:
var TheFile: string;
1B. At program start, set TheFile to an empty string:
TheFile := '';
1C. Before saving to a file, check variable TheFile. If it's empty, show a secondary form, containing an edit box called edFileName and a button. The user enters the filename; next, he clicks the button, and that closes the form.
if Length(TheFile) = 0 then begin Form2.ShowModal; // form stays open until button clicked TheFile := Form2.edFileName.Text; end; if Length(TheFile) = 0 then ShowMessage('Not saved. Need a filename.'); else // ...set up the entire path and save the file // e.g.: save under the name // 'C:\Results' + TheFile + '.txt'
This is still quite basic: even if TheFile is not empty, you should check if it is valid. For example, it can not be only spaces.
2. Simply checking if there are items added is easy: store the number of items at in an integer variable OldNumber program start, and after each saving of the file:
OldNumber := Listbox1.Items.Count;
Before exiting the program, compare the number of items with OldNumber.
But... if you want to save also when the *contents* of (one ore more) item(s) is changed, it is more complicated. You need a backup copy of all the listbox items, for comparing with the current listbox before exiting. You can use a TStringList for this:
var OldList: TStringList;
At program start:
OldList := TStringList.Create;
After each save, copy the items:
OldList.Clear; for i := 0 to ListBox1.Items.Count - 1 do OldList.Add(ListBox1.Items[i]);
Before exiting, compare the lists:
var SaveIt: Boolean; ... SaveIt := ListBox1.Items.Count <> OldList.Items.Count; if (not SaveIt) and (ListBox1.Items.Count > 0) then for i := 0 to ListBox1.Items.Count - 1 do begin SaveIt := ListBox1.Items[i] <> OldList.Items[i]; if SaveIt then break; end; if SaveIt then // ...save the file...
Don't forget, at program end, to free the TStringList:
This is because OldList is an *object* that you created, so you must destroy it in order to have no "memory leaks".