1. Home
  2. Computing & Technology
  3. Delphi Programming

Summing multiple selected rows in a DBGrid

By Zarko Gajic, About.com

1. First use Object Inspector and set True to properties: dgMultiSelect and dgRowSelect. Note that when you set dgRowSelect to true, the dgEditing is automatically set to false.

2. Then, you can use the following function to sum, for example, values in the AField filed in all the rows selected (in the Table1, DBGrid1)!

~~~~~~~~~~~~~~~~~~~~~~~~~
function SUMSomething: Float;
var
  i: Integer;
  Sum: Currency;
begin
  Sum := 0;
  for i := 1 to DBGrid1.SelectedRows.Count do
   begin
    Table1.GotoBookMark
      (Pointer(DBGrid1.SelectedRows.Items[i-1])) ;
    {
     The TDBGrid component keeps all the
     selections as Bookmarks in a
     TStringList, and all the Bookmarks
     must be converted to a Pointer
     (what they really are) before using it.
    }
     Sum := Sum +
            Table1.FieldByName('AField').AsFloat;
   end;
  Result := Sum;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
Here are some more DBGrid related articles and tutorials: DBGrid to the Max

Delphi tips navigator:
» Associate filetype (extension) with your application
« Open an applet from the Control Panel

Zarko Gajic
Guide since 1998

Zarko Gajic
Delphi Programming Guide

Explore Delphi Programming
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Delphi Programming
  4. Coding Delphi Applications
  5. Delphi Tips and Tricks
  6. 2000 Delphi Tips
  7. Summing multiple selected rows in a DBGrid

©2009 About.com, a part of The New York Times Company.

All rights reserved.