Moving rows and columns of a StringGrid by code

Making MoveColumn and MoveRow public without installing a new component

Moving rows and columns of a StringGrid by code

The user can move rows and columns of a StringGrid with the mouse. Can it also be done by code? In the help for TCustomGrid you can see the methods MoveColumn and MoveRow, but they are hidden in TStringGrid. We can make them accessible again by subclassing TStringGrid and declaring these methods as public:



type

    TStringGridX = class(TStringGrid)

    public

      procedure MoveColumn(FromIndex, ToIndex: Longint);

      procedure MoveRow(FromIndex, ToIndex: Longint);

    end;


The implementation of these methods simply consists of invoking the corresponding method of the ancestor:



procedure TStringGridX.MoveColumn(FromIndex, ToIndex: Integer);

  begin



    inherited;

  end;



  procedure TStringGridX.MoveRow(FromIndex, ToIndex: Integer);

  begin

    inherited;

  end;


You don't have to register this component in the Components Palette. Use a TStringGrid or any TCustomGrid descendant, and when you need to call these methods simply cast the object to the new class. For example:



procedure TForm1.Button1Click(Sender: TObject);

  begin

    TStringGridX(StringGrid1).MoveColumn(1, 3);

  end;


You can find the full source code of this article in the archive that accompanies the Pascal Newsletter #25

 

Share this article!

Follow us!

Find more helpful articles: