Mirror

Drag text from one cell to another in a TStringGrid (Views: 101)


Problem/Question/Abstract:

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).

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    Label1: TLabel;
    Label2: TLabel;
    procedure StringGrid1DragOver(Sender, Source: TObject; X, Y: Integer;
      State: TDragState; var Accept: Boolean);
    procedure StringGrid1DragDrop(Sender, Source: TObject; X, Y: Integer);
    procedure StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
  private
    { Private declarations }
    lastcol, lastrow: Integer;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.StringGrid1DragOver(Sender, Source: TObject; X, Y: Integer;
  State: TDragState; var Accept: Boolean);
var
  c, r: Integer;
  pt: TPoint;
begin
  Accept := (Sender = Source) and (lastcol > 0) and (lastrow > 0);
  if Accept then
  begin
    Stringgrid1.MouseToCell(x, y, c, r);
    Accept := (c > 0) and (r > 0);
  end;
end;

procedure TForm1.StringGrid1DragDrop(Sender, Source: TObject; X, Y: Integer);
var
  c, r: Integer;
  pt: TPoint;
begin
  Stringgrid1.MouseToCell(x, y, c, r);
  with Stringgrid1 do
    if (c = lastcol) and (r = lastrow) then
    begin
      col := lastcol;
      row := lastrow;
    end
    else
    begin
      Cells[c, r] := Cells[lastcol, lastrow];
      Cells[lastcol, lastrow] := '';
    end;
end;

procedure TForm1.StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
  Stringgrid1.mousetocell(x, y, lastcol, lastrow);
  Stringgrid1.BeginDrag(false, 5);
end;

end.

<< Back to main page