I use the following code to take the current grid's column list (order, title and width) and save it to a file (and, further down, load a grid from a file)
procedure TSample.saveGridLayout(fileName: string);
var
lines: TStringList;
i: integer;
begin
try
lines := TStringList.Create;
with DBGrid1 do begin
for i := 0 to DBGrid1.Columns.count-1 do begin
lines.Add( IntToStr(DBGrid1.Columns[i].Index)
+ '~ ' + DBGrid1.Columns[i].DisplayName
+ '~ ' + DBGrid1.Columns[i].Title.Caption
+ '~ ' + IntToStr(DBGrid1.Columns[i].Width)
);
end;
end;
lines.SaveToFile(fileName);
finally
lines.free;
end;
end;
procedure TSample.loadGridLayout(fileName: string);
var
lines: TStringList;
columnInfo: TStringList;
lineCtr: integer;
colIdx: integer;
cnt: integer;
begin
try
lines := TStringList.Create;
columnInfo := TStringList.Create;
lines.LoadFromFile(fileName);
for lineCtr := 0 to lines.Count-1 do begin
if trim(lines[lineCtr]) <> '' then begin
StringExplode(lines[lineCtr], '~ ', columnInfo);
cnt:=DBGrid1.Columns.count;
// go through all the columns, looking for the one we are currently working on
for colIdx := 0 to cnt-1 do begin
// once found, set its width and title, then its index (order)
if DBGrid1.Columns[colIdx].FieldName = columnInfo[1] then begin
DBGrid1.Columns[colIdx].Width := StrToInt(columnInfo[3]);
DBGrid1.Columns[colIdx].Title.Caption := columnInfo[2];
// do the index assignment last!
// ignore the index specified in the file. use its line
DBGrid1.Columns[colIdx].Index := lineCtr; //StrToInt(columnInfo[0]); order instead
end; // if
end;
end;
end;
finally
lines.free;
if assigned(columnInfo) then begin
columnInfo.free;
end;
end;
end;
// code for the stringExplode method...
Procedure StringExplode(s: string; Delimiter: string; Var res: TStringList);
Begin
res.Clear;
res.Text := StringReplace(s, Delimiter, #13#10, [rfIgnoreCase, rfReplaceAll]);
End;
Note
Please note that the above is a quick extract from my code, that has been cut down for brevity. Test before deplying.