如何防止在delphi 7中编辑tstringgrid中的unmpty单元格?

use*_*332 3 delphi

在此输入图像描述我有一个问题,需要你的帮助我将在数独游戏上工作.在我的Stringgrid中,我在[grid1.cells [8,8]:= inttostr(2);之前用数字填充了一些单元格.grid1.cells [2,5]:= inttostr(9); 等等]和数字的文字字体颜色是黑色的.现在我希望玩家不能更改(编辑)以前的值,只能添加到空单元格(只能更改自己的值).插入到单元格中的值必须是不同的文本字体颜色(exp:clRed)我在这两种情况下需要帮助.提前致谢 .

TLa*_*ama 6

没有公开的方法来中断单元格编辑过程,但您可以创建一个TStringGrid子类并覆盖其CanEditShow受保护的方法.在此控制子类中,您可以例如创建一个事件来控制是否创建就地编辑器.

下面的插入器类介绍了OnCanEdit在创建inplace编辑器之前触发的事件,并允许您决定是否要通过其CanEdit参数创建它:

type
  TCanEditEvent = procedure(Sender: TObject; Col, Row: Longint;
    var CanEdit: Boolean) of object;

  TStringGrid = class(Grids.TStringGrid)
  private
    FOnCanEdit: TCanEditEvent;
  protected
    function CanEditShow: Boolean; override;
  public
    property OnCanEdit: TCanEditEvent read FOnCanEdit write FOnCanEdit;
  end;

implementation

{ TStringGrid }

function TStringGrid.CanEditShow: Boolean;
begin
  Result := inherited CanEditShow;

  if Result and Assigned(FOnCanEdit) then
    FOnCanEdit(Self, Col, Row, Result);
end;
Run Code Online (Sandbox Code Playgroud)

此示例显示如何仅允许对行和列索引大于2的单元格进行编辑,这不是您的情况,但我确定您了解该怎么做:

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    procedure FormCreate(Sender: TObject);
  private
    procedure StringGridCanEdit(Sender: TObject; Col, Row: Longint; 
      var CanEdit: Boolean);
  end;

implementation

procedure TForm1.FormCreate(Sender: TObject);
begin
  StringGrid1.OnCanEdit := StringGridCanEdit;
end;

procedure TForm1.StringGridCanEdit(Sender: TObject; Col, Row: Integer;
  var CanEdit: Boolean);
begin
  // to the CanEdit parameter assign True if you want to allow the cell
  // to be edited, False if you don't
  CanEdit := (Col > 2) and (Row > 2);
end;
Run Code Online (Sandbox Code Playgroud)