views:

627

answers:

1

Is there any way to copy a selection of rows from a TDBGrid in Delphi 2007 to the clipboard easily?

+4  A: 

This method is from our internal library unit..

procedure BuildListFromDBGrid(DBGrid: TDBGrid; const FieldName: String; Strings :TStrings);
var
  i: Integer;
begin
  Strings.Clear();
  with DBGrid do
     begin
        Strings.BeginUpdate(); // If assocated with a UI control (Listbox, etc), this will prevent any flickering
        DataSource.DataSet.DisableControls();
        try
          for i := 0 to (SelectedRows.Count - 1) do
             begin
               Datasource.DataSet.GotoBookmark(Pointer(SelectedRows[i]));
               Strings.Add(DataSource.DataSet.FieldByName(FieldName).AsString);
             end;
        finally
           DataSource.DataSet.EnableControls();
           Strings.EndUpdate();
        end;
     end;
end;

To get the list of selected items to the clipboard, add Clipbrd to your uses clause and call the procedure..

var
  SelectedItems :TStringList;
begin
  SelectedItems := TStringList.Create();
  try
    BuildListFromDBGrid(MyDBGrid, 'InvoiceID', SelectedItems);
    Clipboard.AsText := SelectedItems.Text;
  finally
    SelectedItems.Free();
  end;
end;

Of course you could modify the above method or create a new one that directly adds the selected items to the clipboard (ex, multiple fields, in a specialized format, etc)

KevinRF
That's handy - thanks! But doesn't it effectively get a 'column' from the grid rather than a 'row'? When I looked at the original question I decided he'd have to have some kind of means of storing fieldname/value pairs onto the clipboard.
robsoft