2010. január 20., szerda

Use my own Inplace-Editors in Grids


Problem/Question/Abstract:

String-Grids are very usefull, but sometimes it's necessary to use an own Inplace-Editor. For example to make a Grid which will allow only numbers but no Text-Characters.

Answer:

When you are using Grids (TStringGrid, TDBGrid), you can input some text in the cells of the grid. This will be done with the "Inplace-Editor" from Borland.

Sometimes it's necessary to make an own Inplace-Editor, for example to prevent the user to give in Text instead of number. The following example shows how to do this.

First you need two new classes: one for your Grid and one for your Inplace-Editor. In this example I use TStringGrid, but it should also work with TDBStringGrid.

unit u_TMyStringGrid;

interface

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

type

  // My own Inplace-Editor. This Editor -for example- only
  // allow numbers, no text
  TMyInplaceEdit = class(TInplaceEdit)
  protected
    procedure KeyPress(var Key: Char); override;
  end;

  // My own StringGrid, which will use my own Inplace-Editor
  TMyStringGrid = class(TStringGrid)
  protected
    function CreateEditor: TInplaceEdit; override;
  end;

implementation

{ TMyStringGrid }
// Here i define, that my StringGrid should use MyInplace-Editor

function TMyStringGrid.CreateEditor: TInplaceEdit;
begin
  Result := TMyInplaceEdit.Create(Self);
end;

{ TMyInplaceEdit }
//The Inplace-Edit only allowes numers, no text-Characters

procedure TMyInplaceEdit.KeyPress(var Key: Char);
begin
  if not (Key in ['0'..'9']) then
  begin
    beep;
    Key := #0
  end
  else
    inherited;
end;

end.

Nincsenek megjegyzések:

Megjegyzés küldése