Search code examples
mysqldelphidelphi-xetstringlisttmemo

How to get values from a field and assign to a TStringList?


How do I get all the username values from the image below and can convert them into TStringList, strings or TMemo?

enter image description here

I tried the following code but it didn't work.

with q3 do
  var txResul:stringlist
  begin
    Close;
    SQL.Clear;
    SQL.Add('SELECT*FROM user');
    Open;
    Next;
  end;
  txtResult.Add(q1.FieldByName('username').AsString);

Solution

  • Assuming your screenshot is a dataset you call do something like this:

    procedure GetUserNames(DataSet : TDataSet; StringList : TStringList);
    var
      Field : TField;
    begin
      Field := DataSet.FieldByName('username');
      StringList.BeginUpdate;      
      try
        DataSet.DisableControls;
        try
          DataSet.First;
          while not DataSet.Eof do begin
            StringList.Add(Field.AsString);
            DataSet.Next;
          end;
        finally
          DataSet.EnableControls;
        end; 
      finally
        StringList.EndUpdate;
      end;
    end;
    

    You might use it like this

    procedure TForm1.GetUsers;
    var
      TL : StringList;
    begin
      TL := StringList.Create;
      try
        GetUserNames(MyTable, TL);
        Memo1.Lines.Text := TL.Text;
      finally
        TL.Free;
      end;
    end;
    

    Btw, if you changed the second parameter of GetUserNames to a TStrings, as in GetUserNames(DataSet : TDataSet; Strings : TStrings) you could pass Memo1.Lines to it directly.