tags:

views:

92

answers:

2

Hi 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

+4  A: 

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;
Serg
+3  A: 

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;
Marjan Venema
Hi Thanks for the quick response,is there also a way to write the contents of a grid to a section in a ini file?Colin
Of course there is. I have updated my answer with an example. I do think however, that you could have come up with this yourself had you taken the trouble to study that example and to read the docs on TIniFile and TStringGrid. I do hope I am not doing your (home)work for you.
Marjan Venema
Thanks for that, I have hit a minor snag, I am uing the ini file to store value / replacement values so for example I am replacing values in a file for example A with B A=B however if I try to save the Value B with a space before it EG A= B then the space is stripped off and I still get A=B is there anyway around it. I am using Delphi 7 Colin
Possibly. It may be related to the grid or to the inifile. Don't know of the top of my head. Besides, I think you should really enter a new question for this. Its kinder to all of us to keep questions and answer focused instead of "deteriorating" into newsgroup like long threads. Plus, it will also draw the attention again of people. Once a question has received a number of answers and especially when one is accepted, it drops off the SO radar so to speak...
Marjan Venema
ok thanksI will create a new question