将tdbgrid的部分复制到剪贴板?

时间:2008-12-29 09:57:12

标签: delphi clipboard

有没有办法轻松地将Delphi 2007中的TDBGrid选择的行复制到剪贴板?

1 个答案:

答案 0 :(得分:5)

此方法来自我们的内部库单元..

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;

要将所选项目列表添加到剪贴板,请将Clipbrd添加到uses子句并调用该过程。

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

当然你可以修改上面的方法或创建一个新的方法直接将所选的项目添加到剪贴板(例如,多个字段,以专门的格式等)