# How to save and load a TStringGrid to and from a file

Here's how the contents of a string grid can be saved to file:

procedure SaveStringGrid(AStringGrid: Grids.TStringGrid; const AFileName: SysUtils.TFileName); var F: TextFile; I, K: Integer; begin AssignFile(F, AFileName); Rewrite(F); with AStringGrid do begin // Write number of Columns/Rows Writeln(F, ColCount); Writeln(F, RowCount); // loop through cells for I := 0 to ColCount - 1 do for K := 0 to RowCount - 1 do Writeln(F, Cells[I, K]); end; CloseFile(F); end;

It can be loaded again using this code:

procedure LoadStringGrid(AStringGrid: Grids.TStringGrid; const AFileName: SysUtils.TFileName); var F: TextFile; Tmp, I, K: Integer; StrTemp: String; begin AssignFile(F, AFileName); Reset(F); with AStringGrid do begin // Get number of columns Readln(F, Tmp); ColCount := Tmp; // Get number of rows Readln(F, Tmp); RowCount := Tmp; // loop through cells & fill in values for I := 0 to ColCount - 1 do for K := 0 to RowCount - 1 do begin Readln(F, StrTemp); Cells[I, K] := StrTemp; end; end; CloseFile(F); end;

Author: | Unknown |
---|---|

Contributor: | Michael Rockett |

Added: | 2010-12-17 |

Last updated: | 2010-12-17 |