I have a form with a ListBox and 2 buttons. I declare a type
TName = class
CustName : string;
end;
var
MyFile : file of TName;
cName : TName;
Then use the following to add or display data:
procedure TForm1.btnAddClick(Sender: TObject);
begin
if Length(edtName.Text)<1 then Exit;
AssignFile(MyFile,'dFile.dat');
FileMode := fmOpenWrite;
if FileExists('dFile.dat') then
begin
Reset(MyFile);
Seek(MyFile,FileSize(MyFile));
end
else
Rewrite(MyFile);
cName := TName.Create;
cName.CustName := edtName.Text;
write(MyFile,cName);
CloseFile(MyFile);
end;
procedure TForm1.btnShowClick(Sender: TObject);
begin
lst1.Clear;
if not FileExists('dFile.dat') then Exit;
AssignFile(MyFile,'dFile.dat');
FileMode := fmOpenRead;
Reset(MyFile);
try
while not Eof(MyFile) do
begin
read(MyFile,cName);
lst1.Items.Add(cName.CustName);
end;
finally
CloseFile(MyFile);
end;
end;
This works fine if the file is created from scratch - I can add data and show it in the Listbox without a problem.
HOWEVER, if the file already exists when I start the program I can add data BUT, when I attempt to show the data, I get an error.
Can someone please point out the error in my ways?
Hannes
TName = class
CustName : string;
end;
var
MyFile : file of TName;
cName : TName;
Then use the following to add or display data:
procedure TForm1.btnAddClick(Sender: TObject);
begin
if Length(edtName.Text)<1 then Exit;
AssignFile(MyFile,'dFile.dat');
FileMode := fmOpenWrite;
if FileExists('dFile.dat') then
begin
Reset(MyFile);
Seek(MyFile,FileSize(MyFile));
end
else
Rewrite(MyFile);
cName := TName.Create;
cName.CustName := edtName.Text;
write(MyFile,cName);
CloseFile(MyFile);
end;
procedure TForm1.btnShowClick(Sender: TObject);
begin
lst1.Clear;
if not FileExists('dFile.dat') then Exit;
AssignFile(MyFile,'dFile.dat');
FileMode := fmOpenRead;
Reset(MyFile);
try
while not Eof(MyFile) do
begin
read(MyFile,cName);
lst1.Items.Add(cName.CustName);
end;
finally
CloseFile(MyFile);
end;
end;
This works fine if the file is created from scratch - I can add data and show it in the Listbox without a problem.
HOWEVER, if the file already exists when I start the program I can add data BUT, when I attempt to show the data, I get an error.
Can someone please point out the error in my ways?
Hannes