Author: Tomas Rutkauskas
I've got a little application that uses a TStringGrid to store an array of
information. I wish to be able to drag the contents of one cell to another. Anyone
out there have any experience of dragging the contents of a StringGrid within the
same grid?
Answer:
Dragging text from one cell to another in a StringGrid (Dragmode = dmManual).
1 unit Unit1;
2
3 interface
4
5 uses
6 Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids,
7 StdCtrls;
8
9 type
10 TForm1 = class(TForm)
11 StringGrid1: TStringGrid;
12 Label1: TLabel;
13 Label2: TLabel;
14 procedure StringGrid1DragOver(Sender, Source: TObject; X, Y: Integer;
15 State: TDragState; var Accept: Boolean);
16 procedure StringGrid1DragDrop(Sender, Source: TObject; X, Y: Integer);
17 procedure StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
18 Shift: TShiftState; X, Y: Integer);
19 private
20 { Private declarations }
21 lastcol, lastrow: Integer;
22 public
23 { Public declarations }
24 end;
25
26 var
27 Form1: TForm1;
28
29 implementation
30
31 {$R *.DFM}
32
33 procedure TForm1.StringGrid1DragOver(Sender, Source: TObject; X, Y: Integer;
34 State: TDragState; var Accept: Boolean);
35 var
36 c, r: Integer;
37 pt: TPoint;
38 begin
39 Accept := (Sender = Source) and (lastcol > 0) and (lastrow > 0);
40 if Accept then
41 begin
42 Stringgrid1.MouseToCell(x, y, c, r);
43 Accept := (c > 0) and (r > 0);
44 end;
45 end;
46
47 procedure TForm1.StringGrid1DragDrop(Sender, Source: TObject; X, Y: Integer);
48 var
49 c, r: Integer;
50 pt: TPoint;
51 begin
52 Stringgrid1.MouseToCell(x, y, c, r);
53 with Stringgrid1 do
54 if (c = lastcol) and (r = lastrow) then
55 begin
56 col := lastcol;
57 row := lastrow;
58 end
59 else
60 begin
61 Cells[c, r] := Cells[lastcol, lastrow];
62 Cells[lastcol, lastrow] := '';
63 end;
64 end;
65
66 procedure TForm1.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
67 Shift: TShiftState; X, Y: Integer);
68 begin
69 Stringgrid1.mousetocell(x, y, lastcol, lastrow);
70 Stringgrid1.BeginDrag(false, 5);
71 end;
72
73 end.
|