第六章-文件管理(一)(4)2007-05-076.2.4 记录文件的读入和显示 定义一个全局变量Count用来保存文件中的记录个数。当文件装入时: Count := FileSize(MethodFile); 如果Count > 0,则首先确定StringGrid1的高度、行数。为保证StringGrid1不会覆盖窗口下面的编辑框,定义一个常量MaxShow。当Count < MaxShow时,记录可全部显示;当Count >= MaxShow时,StringGrid1自动添加一个滚动棒。为保证滚动棒不覆盖掉显示内容,StringGrid1的宽度应留有余地。确定StringGrid1高度、行数的代码如下: With StringGrid doif count < MaxShow thenHeight := DefaultRowHeight * (Count+1)+10elseHeight := DefaultRowHeight * MaxShow+10;RowCount := Count+1;end; 而后从文件中逐个读入记录并显示在StringGrid1的相应位置: for i := 1 to Count do beginRead(MethodFile,MethodRec);ShowMethod(MethodRec,i);end; ShowMehtod是一个过程,用来把一条记录填入StringGrid1的一行中。对于Name、Condition域而言,只须直接赋值即可;而对Nature 域需要把枚举类型值转化为对应意义的字符串(0:“微观”,1:“宏观”);而对Result域则需要把数值转化为一定格式的字符串: Str (MethodRec.Result:6:4,ResultStr); StringGrid1.Cells[3,Pos] := ResultStr; 即Result显示域宽为6,其中小数点后位数为4。 6.2.5 增加一条记录 当用户单击“增加”按钮时屏幕将会弹出一个记录编辑模式对话框EditForm。在编辑框中填入合适的内容并按OK键关闭后,相应值写入一个TMethod类型的变量MethodRec中。其中Nature和Result 域需要进行转换。之后增加的记录添加到StringGrid1的显示中。最后文件定位于尾部,写入当前记录,总记录数加1。 Seek(MethodFile,Count);Write(MethodFile,MethodRec);Count := Count+1; 完整的程序清单如下: procedure TRecFileForm.AddButtonClick(Sender: TObject);varMethodRec: TMethod;Rl: Real;k: Integer;EditForm: TEditForm;beginif FileOpenEd = False then Exit;EditForm := TEditForm.Create(self);if EditForm.ShowModal <> idCancel thenbeginHazAttr.text := "";MethodRec.Name := EditForm.MethodName.text;MethodRec.Condition := EditForm.Condition.text;case EditForm.NatureCombo.ItemIndex of0:MethodRec.Nature := Micro;1:MethodRec.Nature := Macro ;end;Val(EditForm.Result.text,Rl,k);MethodRec.Result := Rl;with StringGrid1 dobeginif Count < MaxShow thenHeight := Height+DefaultRowHeight;RowCount := RowCount+1;end;ShowMethod(MethodRec,Count+1);seek(MethodFile,Count);write(MethodFile,MethodRec);Count := Count+1;end;end; 6.2.6 修改记录 首先获取当前记录位置: CurrentRec := StringGrid1.Row - 1; 而后打开编辑对话框并显示当前值。修改完毕后,修改结果保存在一个记录中并在StringGrid1中重新显示。最后修改结果写入文件: Seek(MethodFile,CurrentRec);Write(MethodFile,MethodRec); 完整程序如下: procedure TRecFileForm.ModifyButtonClick(Sender: TObject);varMethodRec: TMethod;Rl: Real;k: Integer;EditForm: TEditForm;beginif FileOpened = False then Exit;EditForm := TEditForm.Create(self);CurrentRec := StringGrid1.Row-1;with EditForm dobeginMethodName.text := StringGrid1.Cells[0,CurrentRec+1];Condition.text := StringGrid1.Cells[1,CurrentRec+1];if StringGrid1.Cells[2,CurrentRec+1] = "微 观" thenNatureCombo.ItemIndex := 0elseNatureCombo.ItemIndex := 1;Result.text := StringGrid1.Cells[3,CurrentRec+1];if ShowModal <> idCancel thenbeginHazAttr.text := "";MethodRec.Name := MethodName.text;MethodRec.Condition := Condition.text;case NatureCombo.ItemIndex of0:MethodRec.Nature := Micro;1:MethodRec.Nature := Macro ;end;Val(Result.text,Rl,k);MethodRec.Result := Rl;ShowMethod(MethodRec,CurrentRec+1);seek(MethodFile,CurrentRec);write(MethodFile,MethodRec);end;end;end;