今天下午写了个控件(这是我第一次写控件呢),可以初步解决这个问题。
设置控件的 Table 属性后即可执行 CopyRecord 和 PasteRecord.
KeyFields 属性用来指定关键字,多个关键字可以用";"隔开,Paste
时关键字不会被复制。编写匆忙,错误难免,仅供参考。
unit DBClipBoard;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, Dialogs, Db, DBTables;
type
TDBClipBoard = class(TComponent)
private
FTable: TTable;
FSyncTable: TTable;
FKeyFields: string;
FKeyFieldList: TStringList;
FBookMark: TBookMark;
procedure SetTable(ATable: TTable);
procedure SetKeyFields(AKeyFields: string);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CopyRecord;
procedure PasteRecord;
published
property Table: TTable read FTable write SetTable;
property KeyFields: string read FKeyFields write SetKeyFields;
end;
procedure Register;
implementation
constructor TDBClipBoard.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FSyncTable := TTable.Create(Self);
FKeyFieldList := TStringList.Create;
end;
destructor TDBClipBoard.Destroy;
begin
FSyncTable.Free;
FKeyFieldList.Free;
inherited Destroy;
end;
procedure TDBClipBoard.SetTable(ATable: TTable);
begin
FTable := ATable;
end;
procedure TDBClipBoard.SetKeyFields(AKeyFields: string);
var
i: integer;
s: string;
begin
FKeyFields := AKeyFields;
FKeyFieldList.Clear;
while Length(AKeyFields) > 0 do
begin
i := Pos(';', AKeyFields);
if i <= 0 then
begin
i := Length(AKeyFields);
s := AKeyFields;
end
else
s := Copy(AKeyFields, 1, i - 1);
Delete(AKeyFields, 1, i);
s := Trim(s);
FKeyFieldList.Add(s);
end;
end;
procedure TDBClipBoard.CopyRecord;
begin
if (FTable <> nil) and FTable.Active and (FTable.RecordCount > 0) then
FBookMark := FTable.GetBookMark;
end;
procedure TDBClipBoard.PasteRecord;
var
i: integer;
begin
if (FTable <> nil) and FTable.Active and not FTable.ReadOnly then
begin
FSyncTable.Close;
FSyncTable.DatabaseName := FTable.DatabaseName;
FSyncTable.TableName := FTable.TableName;
FSyncTable.Open;
FSyncTable.Refresh;
try
FSyncTable.GotoBookMark(FBookMark);
except
Exit;
end;
FTable.Append;
for i := 0 to FSyncTable.FieldCount - 1 do
if FKeyFieldList.IndexOf(FTable.Fields.FieldName) < 0 then
FTable.Fields.Assign(FSyncTable.Fields);
end
end;
procedure Register;
begin
RegisterComponents('Samples', [TDBClipBoard]);
end;
end.