Author: Tomas Rutkauskas
I have a form with 4 StringGrids which I fill at run time with data. It takes some
time to enter the data and so I thought it would save me some time if I could save
and load the form with its data - something I've never done in Delphi before. I've
sorted the menu and the dialogue boxes but what method do I have to write to save
the form, its StringGrids and the data therein - simply?
Answer:
You will have noticed that the StringGrid is a control that does not allow you to
enter strings into it at design-time. The reason is that the streaming system
cannot handle array properties like Cells, so the standard component streaming is
no use for your task. But you can write your own routines to save a StringGrids
content, of course. Something like this for example:
1 2 procedure SaveGridToStream(aStream: TStream; aGrid: TStringGrid);
3 var4 i, k: Integer;
5 iBuf: Integer;
6 S: string;
7 8 procedure WrInt(anInt: Integer);
9 begin10 aStream.WriteBuffer(anInt, Sizeof(anInt));
11 end;
12 13 begin14 with aGrid do15 begin16 WrInt(ColCount);
17 WrInt(rowCount);
18 for i := 0 to rowCount - 1 do19 for k := 0 to colCount - 1 do20 begin21 S := Cells[k, i];
22 WrInt(Length(S));
23 if Length(S) > 0 then24 aStream.WriteBuffer(S[1], Length(S));
25 end;
26 end;
27 end;
28 29 procedure LoadGridFromStream(aStream: TStream; aGrid: TStringGrid);
30 var31 i, k: Integer;
32 iBuf: Integer;
33 S: string;
34 35 function RdInt: Integer;
36 begin37 aStream.ReadBuffer(Result, Sizeof(Result));
38 end;
39 40 begin41 with aGrid do42 begin43 ColCount := RdInt;
44 RowCount := RdInt;
45 for i := 0 to rowCount - 1 do46 for k := 0 to colCount - 1 do47 begin48 iBuf := RdInt;
49 if iBuf > 0 then50 begin51 SetLength(S, iBuf);
52 aStream.ReadBuffer(S[1], iBuf);
53 Cells[k, i] := S;
54 end;
55 end;
56 end;
57 end;