colin
colin

Reputation: 3103

ini file section to stringgrid

Could someone know / give me an example of how to read a section from an ini file into a stringGrid? As I am struggling to figure out how to do it.

thanks

Colin

Upvotes: 2

Views: 2385

Answers (2)

Marjan Venema
Marjan Venema

Reputation: 19356

OTOMH:

procedure ReadIntoGrid(const aIniFileName, aSection: string; const aGrid: TStringGrid);
var
  Ini: TIniFile;
  SL: TStringList;
  i: Integer;
begin
  SL := TStringList.Create;
  try
    Ini := TIniFile.Create(aIniFileName);
    try
      aGrid.ColCount := 2;
      Ini.ReadSectionValues(aSection, SL);
      aGrid.RowCount := SL.Count;
      for i := 0 to SL.Count - 1 do
      begin
        aGrid.Cells[0,i] := SL.Names[i];
        aGrid.Cells[1,i] := SL.ValueFromIndex[i];
      end;
    finally
      Ini.Free;
    end;
  finally
    SL.Free;
  end;
end;

EDIT

The other way round:

procedure SaveFromGrid(const aIniFileName, aSection: string; const aGrid: TStringGrid);
var
  Ini: TIniFile;
  i: Integer;
begin
  Ini := TIniFile.Create(aIniFileName);
  try
    for i := 0 to aGrid.RowCount - 1 do
      Ini.WriteString(aSection, aGrid.Cells[0,i], aGrid.Cells[1,i]);
  finally
    Ini.Free;
  end;
end;

Upvotes: 6

kludg
kludg

Reputation: 27493

You are better to use TValueListEditor to show a section of an ini-file.

Here is a simple demo code:

procedure TForm1.Button1Click(Sender: TObject);
var
  SL: TStrings;
  IniFile: TMemIniFile;
begin
  SL:= TStringList.Create;
  try
    IniFile:= TMemIniFile.Create('test.ini');
    try
      IniFile.ReadSectionValues('FOLDERS', SL);
      ValueListEditor1.Strings.Assign(SL);
    finally
      IniFile.Free;
    end;
  finally
    SL.Free;
  end;
end;

Upvotes: 7

Related Questions