不同情况下运行的结果不一样,郁闷中~~~~~~~~
用stringgrid控件读取文本文件,stringgrid与文本文件的行号和列号一一对应。
文本文件内容为
a,1
b,2
c,3
对应stringgrid有三行两列,6个cell,逗号作为分隔符。
现有一个listbox,items如下,item项包含文本文件第一列的内容。
a
b
c
d
e
要求
选择listbox中的一个item,点击按钮,按钮过程为
如果选中的item与stringgrid第一列的某一行(也即文本文件的对应值)相等,则修改将此行修改,例如,选中b,因stringgrid的第2行为b,则将此行修改为
"b,新值(取自label.caption的内容)"
如果选中的item在stringgrid中无对应项,则添加
如,选中e,则在文本文件中新加
"e,新值(取自label.caption的内容)"
现在的问题是
程序在运行时(中途不关闭),以上功能都可实现。但是在程序退出,再重新运行时,对于选中的item在stringgrid中有对应项的情况会进行添加而不是修改操作!!
======================
附代码(文本文件名此处为评分汇总.file)
procedure TForm1.Button1Click(Sender: TObject);
var
onerow:string;
statistics:tstringlist;
rownum:integer;
begin
statistics:=tstringlist.Create;
onerow:=listbox1.items[listbox1.itemindex]+label1.caption;
//如果不存在评分汇总.file则创建。
if not FileExists('评分汇总.file') then statistics.SaveToFile('评分汇总.file');
statistics.LoadFromFile('评分汇总.file');
for rownum:=0 to statistics.count-1 do
begin
if comparetext(stringgrid1.Cells[0,rownum],listbox1.items[listbox1.itemindex])=0 then
begin
statistics.Strings[rownum]:=onerow;//修改特定行
break;//跳出循环
end
//如果没有和listbox相匹配的项则添加一行
else if rownum=statistics.count-1 then
statistics.add(onerow);
end;
//如果文本文件是空文件,则添加第一行
if statistics.count=0 then statistics.add(onerow);
statistics.SaveToFile('评分汇总.file');
statistics.Free;
end;