Search code examples
delphidelphi-7tstringgrid

Does range checking on TStringGrid cells work?


Below is code for a simple Delphi form application that sets cell values that are out of range for the specified TStringGrid that contains the cells.

Running the program and clicking on the resulting grid on the displayed form should generate a run time range check error when the counter i gets above 1.

Range checking is enabled in the project options, and I have tried running the program with and without the {R+} compiler directive.

Why is there no range check error?

I am using Delphi7 running on Windows 7 (64 bit).

unit Unit1;

interface

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

type
  TForm1 = class(TForm)
    StringGrid1: TStringGrid;
    procedure StringGrid1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}
{$R+} 
procedure TForm1.StringGrid1Click(Sender: TObject);
var
    i : Integer;
begin
    Form1.StringGrid1.ColCount := 2;
    Form1.StringGrid1.RowCount := 3;
    for i := 0 to Form1.StringGrid1.RowCount do begin
        Form1.StringGrid1.Cells[0,i+1] := IntToStr(i);
    end;
end;

end.

Solution

  • From the documentation (emphasis added):

    The $R directive enables or disables the generation of range-checking code. In the {$R+} state, all array and string-indexing expressions are verified as being within the defined bounds, and all assignments to scalar and subrange variables are checked to be within range. If a range check fails, an ERangeError exception is raised (or the program is terminated if exception handling is not enabled).

    TStringGrid cells references are not among the types of variables and assignments that are subject to range checking.