大家看看,问题出在哪儿?为什么listview只宣示链表的最后一个数据.(50分)

  • 主题发起人 主题发起人 风云再起
  • 开始时间 开始时间

风云再起

Unregistered / Unconfirmed
GUEST, unregistred user!
Unit Main;
......
type
//记录结构
PUser = ^TUser;
TUser = record
Name: string[20];
Sex: string[2];
end;

type
TFrm = class(TForm)
Button1: TButton;
Button2: TButton;
lbUser: TListBox;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
procedure LoadUsers(ARecFile: TFileStream);
procedure SaveUsers(ARecFile: TFileStream);
public
{ Public declarations }
end;

var
Frm: TFrm;
UserList: TList; //链表
RecFile: TFileStream; //文件

implementation
uses Unit1;
{$R *.DFM}


procedure TFrm.LoadUsers(ARecFile: TFileStream);
var
AUser: PUser;
begin
//将文件读入链表
with ARecFile do
begin
Position := 0;
while Position < Size do
begin
New(AUser);
Read(AUser^, SizeOf(TUser));
UserList.Add(AUser);
end;
end;
end;

procedure TFrm.SaveUsers(ARecFile: TFileStream);
begin
//将链表数据写入文件
with ARecFile do
begin
Size := 0;
while UserList.Count > 0 do
begin
Write(TUser(UserList[0]^), SizeOf(TUser));
Dispose(PUser(UserList[0]));
UserList.Delete(0);
end;
end;
end;

procedure TFrm.FormCreate(Sender: TObject);
begin
UserList := TList.Create;
if FileExists('UserList.Dat') then
begin
RecFile := TFileStream.Create('UserList.Dat', {fmCreate} fmOpenReadWrite);
LoadUsers(RecFile);
end
else
RecFile := TFileStream.Create('UserList.Dat', fmCreate);
end;

procedure TFrm.FormDestroy(Sender: TObject);
begin
SaveUsers(RecFile);
UserList.Free;
RecFile.Free;
end;

procedure TFrm.Button1Click(Sender: TObject);
var
i: Integer;
AUser: PUser;
begin
//产生数据
for i := 0 to 9 do
begin
New(AUser);
AUser.Name := 'Name' + IntToStr(i);
AUser.Sex := IntToStr(i);
UserList.Add(AUser);
end;
end;

procedure TFrm.Button2Click(Sender: TObject);
var
i: Integer;
begin
//显示文件数据
with lbUser.Items do
begin
BeginUpdate;
Clear;
for i := 0 to UserList.Count - 1 do
Add('姓名:' + TUser(UserList^).Name
+ #9'性别:' + TUser(UserList^).Sex);
EndUpdate;
end;
end;

procedure TFrm.Button3Click(Sender: TObject);
begin
Form1.Show;
end;
Unit Unit1;
...
procedure TForm1.Button1Click(Sender: TObject);
var
i:Integer;
Item:TListItem;
begin
ListView1.Items.Clear;
Item:=ListView1.Items.Add;
for i:=0 to UserList.Count-1 do
begin
Item.Caption:=TUser(UserList^).Name;
Item.SubItems.Add(TUser(UserList^).Sex);
end;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
AUser:PUser;
begin
AUser:=New(PUser);
AUser^.Name:=Edit1.Text;
AUser^.Sex:=Edit2.Text;
UserList.Add(AUser);
end;
 
procedure TForm1.Button1Click(Sender: TObject);
var
i:Integer;
Item:TListItem;
begin
ListView1.Items.Clear;
Item:=ListView1.Items.Add; ------将这一行放入循环体中
for i:=0 to UserList.Count-1 do
begin
Item.Caption:=TUser(UserList^).Name;
Item.SubItems.Add(TUser(UserList^).Sex);
end;
end;

 
哎,郁闷.这么低级的错误.
 
后退
顶部