Copying Data From DBGrid to ListView

Hi all,

Is it possible to copy all contents (Including Headers) from a DBGrid to a ListView?

If so how?

Thanks

ST3VO
ST3VOAsked:
Who is Participating?
 
mikelittlewoodConnect With a Mentor Commented:
Well assuming there is a query attached to the grid, loop through the record set

var
   i: smallInt;
   slFields: TStringList;
   lsti: TListItem;
   lci: TListColumn;
begin
   DBGrid1.DataSource.DataSet.DisableControls;
   try
      slFields := TStringList.Create;
      try
         DBGrid1.DataSource.DataSet.GetFieldNames( slFields);
         // add required number of columns
         for i := 0 to slFields.Count - 1 do
         begin
            lci := ListView1.Columns.Add;
            lci.Caption := slFields.Strings[ i];
         end;

         // now add the data
         DBGrid1.DataSource.DataSet.first;
         while not DBGrid1.DataSource.DataSet.Eof do
         begin
            lsti := ListView1.Items.Add;
            for i := 0 to slFields.Count - 1 do
            begin
               if i = 0 then
                  lsti.Caption := DBGrid1.DataSource.DataSet.fieldByName( slFields.strings[ i]).AsString
               else
                  lsti.SubItems.Add( DBGrid1.DataSource.DataSet.fieldByName( slFields.strings[ i]).AsString);
            end;

            DBGrid1.DataSource.DataSet.Next;
         end;
      finally
         freeAndNil( slFields);
      end;
   finally
      DBGrid1.DataSource.DataSet.first;
      DBGrid1.DataSource.DataSet.EnableControls;
   end;

you can also replace DBGrid1.DataSource.DataSet with the name of the query
0
 
ST3VOAuthor Commented:
Wow..PERFECT!!! :o)

Thanks a million!

p's: Mike I know that you know about TMS Components and I've got a couple of questions opened on that.
I just thought I'd let you know in case you wanted to have a look at them.

Anyway, that worked GREAT!!!

Cheers

ST3VO
0
 
mikelittlewoodCommented:
Sure I'll take a quick look, was just about to comment on the AdvDBGrid one you have open.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.