How to use Listview correctly in delphi?

Rafik Bari picture Rafik Bari · Dec 23, 2011 · Viewed 50.5k times · Source

My code is the below, it's working correctly but, but after compiling program i see all the fullname and country listed vertically something like :

_________________________________
Fullname1
Country1
Fullname2
Country2
Fullname3
Country3
etc...

SQLQuery1.SQL.Text := 'SELECT * FROM users where user_age="'+age+'"';
SQLQuery1.Open;
rec := SQLQuery1.RecordCount;

SQLQuery1.First; // move to the first record
ListView1.Visible := false;
if rec>0 then
begin
while(not SQLQuery1.EOF)do begin
ListView1.Visible := true;
        // do something with the current item
ListView1.AddItem('Full name: '+SQLQuery1['fullname'], Self);
ListView1.AddItem('Country: '+SQLQuery1['cntry'], Self);

    // move to the next record

SQLQuery1.Next;

end;

But i want something Like :

enter image description here

Answer

Marjan Venema picture Marjan Venema · Dec 23, 2011

First: add the column headers:

var
  Col: TListColumn;
begin
  Col := ListView1.Columns.Add;
  Col.Caption := 'Name';
  Col.Alignment := taLeftJustify;
  Col.Width := 140;

  Col := ListView1.Columns.Add;
  Col.Caption := 'Country';
  Col.Alignment := taLeftJustify;
  Col.Width := 140;
end;

then add the records as follows:

var
  Itm: TListItem;
begin
    // start of your query loop
    Itm := ListView1.Items.Add;
    Itm.Caption := SQLQuery1['fullname'];
    Itm.SubItems.Add(SQLQuery1['cntry']);
    // end of your query loop
end;

Update:

Of course, in order to get the list as in your screenshot, you need to set the ListView's ViewStyle property to vsReport