Search code examples
delphidelphi-xedelphi-xe7

Read all section .ini values into stringgrid


I use Delphi XE7. Is there any way to load all values from an .ini file into a stringgrid in different coloumns?

My .ini file looks like

[1038]
AValue = a1 
BValue = b1
CValue = c1
DValue = d1

[1031]
AValue = a2 
BValue = b2
CValue = c2
DValue = d2

I use this procedure for filling the grid:

procedure TForm1.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;

It works fine, I get this:

enter image description here

My question is...
How can I read all section values (1038 and 1031) into the grid next to the 1038 values? Values will be fixed all time.

enter image description here


Solution

  • To give you some ideas:

    First, i think you should add one paramater to your procedure:

    procedure TForm1.ReadIntoGrid(const aIniFileName, aSection: string;
    const aGrid: TStringGrid; const aColumn: Integer = 1);
    

    Second, rewrite this part of your method :

      for i := 0 to SL.Count - 1 do
      begin
        aGrid.Cells[0,i] := SL.Names[i];
        aGrid.Cells[1,i] := SL.ValueFromIndex[i];
      end;
    

    replace with

      for i := 0 to SL.Count - 1 do
      begin
        aGrid.Cells[0,i] := SL.Names[i];
        aGrid.Cells[aColumn,i] := SL.ValueFromIndex[i];
      end;
    

    ps: Obviously you dont nead to rewrite the value into the first column.

    So now assume you are calling the method like this:

    ReadIntoGrid('MyIniFile.ini','1038', MyGrid, 1);
    ReadIntoGrid('MyIniFile.ini','1031', MyGrid, 2);