Search code examples
delphidelphi-7

Delphi, search in text file


So, I have edit1 and edit2 + button on the form when I put some number to edit1, after on button_clik it will search 12345 in the specified text file, if found, read string after delimiter or all line and pu it to edit2.

the code:

procedure TForm1.Button1Click(Sender: TObject);  var   sl : TStringList;   ix : Integer;

begin   sl := TStringList.Create;   try
    sl.LoadFromFile('C:\Polozky.txt');
    ix := sl.IndexOf(Edit1.Text);
    //d := SL.ValueFromIndex[IX];
    if ix > -1 then ShowMessage('OK')  Else ShowMessage('NOTHING');   finally
    sl.Free;   end; end;

hELLO, yes my file is comma seperated

12345,CAR
12233,BUS

..... i would like to find 12345 adn put CAR into edit2.


Solution

  • tStringList.Values will search for a string of the form Name=Value. If you want to use a different delimiter, such as comma, set NameValueSeparator. The code below displays the message 'BUS'.

    var
      SL : tStringList;
    begin
      SL := tStringList . Create;
    
      SL . Add ( '12345,CAR' );
      SL . Add ( '12233,BUS' );
    
      SL . NameValueSeparator := ',';
    
      ShowMessage ( SL . Values [ '12233' ] );
    end;