Search code examples
delphidelphi-xe4tstringlist

Delphi load name/value pair from text file


Want to load name value pairs into a TStringList.

have a text file with data:

a=ant
a=animal
b=bob
d=darn

Function to load it:

LoadData(argPath: string): TStringList;
var
  data: TStringList;
begin
  data := TStringList.Create(true);
  data.Delimiter := '=';
  try
    data.LoadFromFile(argPath);
  except on E : Exception do
  begin
    Application.MessageBox(PWideChar(E.Message), 
       'Unable to Load Data', MB_OK or MB_ICONERROR);
    Application.Terminate;
  end;
  end;
  Result := data;
end;

Result is currently:

a=ant
a=animal
b=bob
d=darn

want the Result's strings to be:

ant
animal
bob
darn

and the Result's TObjects to be

a
a
b
d

After this I want to be able to display this in a TComboBox.


Solution

  • You'll have to use the built-in functions in the TStringList. I've broken this down into variables just for ease of reading / understanding, but could be compacted:

    var
      X: Integer;
      Name, Value: String;
    begin
      for X:= 0 to MyList.Count - 1 do begin
        Name:= MyList.Names[X];
        Value:= MyList.ValueFromIndex[X];
        MyCombo.Items.Add(Value);
      end;
    end;
    

    With that, I'm sure you can figure out the rest (since I'm not sure exactly what you mean by result strings and objects).