unit uMemo;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, ExtCtrls, DBCtrls, Db, DBGrids, ABSMain;

type
  TfMemo = class(TForm)
    Panel2: TPanel;
    btOk: TButton;
    Panel1: TPanel;
    GroupBox1: TGroupBox;
    Panel4: TPanel;
    Panel3: TPanel;
    btLoad: TButton;
    btSave: TButton;
    MemoField: TDBMemo;
    odMemo: TOpenDialog;
    sdMemo: TSaveDialog;
    btCancel: TButton;
    lSize: TLabel;
    Label1: TLabel;
    procedure FormShow(Sender: TObject);
    procedure btLoadClick(Sender: TObject);
    procedure btSaveClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure btOkClick(Sender: TObject);
    procedure btCancelClick(Sender: TObject);
  private
    { Private declarations }
  public
    CurrentTable: TABSDataset;
    CurrentGrid: TDBGrid;
    { Public declarations }
  end;

var
  fMemo: TfMemo;

implementation

{$R *.DFM}

procedure TfMemo.FormShow(Sender: TObject);
begin
 CurrentTable := TABSDataset(CurrentGrid.DataSource.DataSet);
 if (not CurrentTable.ReadOnly) then
   CurrentTable.Edit;
 with MemoField do
   begin
     DataSource := nil;
     DataField := CurrentGrid.SelectedField.FieldName;
     DataSource := CurrentGrid.DataSource;
   end;
 lSize.Caption := Format('%d bytes', [Length(MemoField.Text)]);
 Caption := Format('Memo Field "%s"',[CurrentGrid.SelectedField.FieldName]);
end;

procedure TfMemo.btLoadClick(Sender: TObject);
var
  FileStream: TFileStream;
  BlobStream: TABSBlobStream;
begin
 if (odMemo.Execute) then
   begin
     MemoField.DataSource := nil;
     try
       BlobStream := TABSBlobStream(CurrentTable.CreateBlobStream(CurrentGrid.SelectedField, bmWrite));
       FileStream := TFileStream.Create(odMemo.FileName, fmOpenRead or fmShareDenyNone);
       BlobStream.CopyFrom(FileStream,FileStream.Size);
       lSize.Caption := Format('%d bytes', [FileStream.Size]);
       FileStream.Free;
       BlobStream.Free;
     finally
       MemoField.DataSource := CurrentGrid.DataSource;
     end;
   end;
end;

procedure TfMemo.btSaveClick(Sender: TObject);
var
  FileStream: TFileStream;
  BlobStream: TStream;
begin
  if (sdMemo.Execute) then
    begin
      BlobStream := CurrentTable.CreateBlobStream(CurrentGrid.SelectedField,bmRead);
      FileStream := TFileStream.Create(sdMemo.FileName,fmCreate);
      FileStream.CopyFrom(BlobStream,BlobStream.Size);
      FileStream.Free;
      BlobStream.Free;
    end;
end;

procedure TfMemo.FormClose(Sender: TObject; var Action: TCloseAction);
begin
   MemoField.DataSource := nil;
   if (CurrentTable.State = dsEdit) then
     CurrentTable.Cancel;
end;

procedure TfMemo.btOkClick(Sender: TObject);
begin
  if (not CurrentTable.ReadOnly) then
    CurrentTable.Post;
end;

procedure TfMemo.btCancelClick(Sender: TObject);
begin
  if (not CurrentTable.ReadOnly) then
    CurrentTable.Cancel;
end;

end.

