DELPHI: Two dimensional Arrays & StringGrid
 

Indexes

Indexes are used in string variables where if sSurname contains ?Smith? then sSurname[2] will be ?m? because that is the second character of the variable.
sSurname
1 2 3 4 5
S m i t h

The number used to refer to a certain character is called the index and is placed in square brackets.

Some components do not start with an index of 1; the ListBox starts at 0.

Therefore the first item in a ListBox has an index of 0.

An array variable can be used to store many data items of the same kind under the same name. Each item is distinguished from the other using an index.

Arrays must be declared under the var and a range must be set, for example:
var
  arrNames : array[1..20] of String;
  arrAges : array[1..1000] of Integer;

The array arrNames can contain up to 20 names (String data type).
The array arrAges can contain up to 1000 integer values.

What is a two dimensional array or matrix?

A two dimensional array consists of:
- a finite,
- ordered set of elements
- of the same data type.

Two dimensional arrays OR matrices are declared in the same way as normal arrays:
var
  arrNames : array[1..20, 1..20] of String;
  arrAges : array[1..5, 1..1000] of Integer;


The array arrNames can contain up to 20 names (String data type) under 20 headings.
The array arrAges can contain up to 1000 integer values under 5 headings.

We can therefore say when declaring a 2D array or Matrix the first range is the column and the second the different rows. This is also true for the StringGrid component.

StringGrid1.Cells[Column,Row]

StringGrid1.Cells[4,1] := 'Hi'; gives:


Sample activities:

1) Fill a StringGrid component with the times tables from 1 to 10.

procedure TForm1.Button1Click(Sender: TObject);
var
  iC, iR, iAns : integer;
begin
  For iC := 0 to 9 do
  begin
    For iR := 0 to 9 do
    begin
     iAns := (iC+1) * (iR+1);
     StringGrid1.Cells[iC,iR] := IntToStr(iAns);
    end;
   end;
end;



2) Clear StringGrid component

procedure TForm1.Button2Click(Sender: TObject);
var
  iC2, iR2 : integer;
begin
  For iC2 := 0 to 9 do
  begin
    For iR2 := 0 to 9 do
    begin
     StringGrid1.Cells[iC,iR] := '';
    end;
   end;
end;


Take note that there are no spaces between the inverted commas ('') in the second activity.
 

Return to Delphi resources index




Return to Home Page

? 2024 TeachITZA. Except where otherwise noted, the content on this website is licensed under the terms of the Creative Commons BY SA 4.0 license. https://creativecommons.org/about/cclicenses/