Marco Web Center

[an error occurred while processing this directive]

Home: Code Repository: Mastering Delphi 6

Chapter 13 - Project DragToGrid

Project Structure

DragToGrid.dpr
program dragtogrid;

uses
  Forms,
  DragToGridForm in 'DragToGridForm.pas' {FormDrag};

{$R *.RES}

begin
  Application.Initialize;
  Application.CreateForm(TFormDrag, FormDrag);
  Application.Run;
end.
DragToGridForm.pas
unit DragToGridForm;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls, Db, DBTables, Grids, DBGrids;

type
  TFormDrag = class(TForm)
    DBGrid1: TDBGrid;
    DataSource1: TDataSource;
    Table1: TTable;
    LabelDrag: TLabel;
    EditDrag: TEdit;
    procedure DBGrid1DragDrop(Sender, Source: TObject; X, Y: Integer);
    procedure DBGrid1DragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  FormDrag: TFormDrag;

implementation

{$R *.DFM}

type
  TDBGHack = class (TDbGrid)
  end;

procedure TFormDrag.DBGrid1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
  gc: TGridCoord;
begin
  gc := TDBGHack(DbGrid1).MouseCoord (x, y);
  if (gc.y > 0) and (gc.x > 0) then
  begin
    DbGrid1.DataSource.DataSet.MoveBy (gc.y - TDBGHack(DbGrid1).Row);
    DbGrid1.DataSource.DataSet.Edit;
    DBGrid1.Columns.Items [gc.X - 1].Field.AsString := EditDrag.Text;
  end;
  DBGrid1.SetFocus;
end;

procedure TFormDrag.DBGrid1DragOver(Sender, Source: TObject; X, Y: Integer;
  State: TDragState; var Accept: Boolean);
begin
  Accept := (Source = LabelDrag);
end;

end.
DragToGridForm.dfm
object FormDrag: TFormDrag
  Left = 243
  Top = 107
  Width = 609
  Height = 345
  Caption = 'DragToGrid'
  Color = clBtnFace
  Font.Charset = DEFAULT_CHARSET
  Font.Color = clWindowText
  Font.Height = -11
  Font.Name = 'MS Sans Serif'
  Font.Style = []
  OldCreateOrder = False
  PixelsPerInch = 96
  TextHeight = 13
  object LabelDrag: TLabel
    Left = 24
    Top = 16
    Width = 314
    Height = 13
    Caption =
       'Enter a value in the edit and drag the label over the target gri' +
      'd cell:'
    DragMode = dmAutomatic
  end
  object DBGrid1: TDBGrid
    Left = 24
    Top = 56
    Width = 553
    Height = 225
    DataSource = DataSource1
    TabOrder = 0
    TitleFont.Charset = DEFAULT_CHARSET
    TitleFont.Color = clWindowText
    TitleFont.Height = -11
    TitleFont.Name = 'MS Sans Serif'
    TitleFont.Style = []
    OnDragDrop = DBGrid1DragDrop
    OnDragOver = DBGrid1DragOver
  end
  object EditDrag: TEdit
    Left = 24
    Top = 32
    Width = 313
    Height = 21
    Color = clWindow
    TabOrder = 1
    Text = 'New Value'
  end
  object DataSource1: TDataSource
    DataSet = Table1
    Left = 496
    Top = 72
  end
  object Table1: TTable
    Active = True
    DatabaseName = 'DBDEMOS'
    TableName = 'country.db'
    Left = 496
    Top = 16
  end
end