Is it possible to change the text in a StringGrid cell immediately after adding a new row or column in Lazarus/Delphi?

1.1k Views Asked by At

I am trying to perform:

Form3.StringGrid1.Cells[0,Form3.StringGrid1.RowCount] := 'Hoofdstad'; 

after performing:

Onderdelen := Form3.StringGrid1.RowCount;
Form3.StringGrid1.RowCount := Onderdelen + 1;

It gives an error every time, it will say that I am trying to change the text of a cell that doesnt exist (yet). I am still very new to this language, I hope someone can help me out.

1

There are 1 best solutions below

0
Remy Lebeau On BEST ANSWER

The Cells property uses 0-based indexing. The index of the first row is 0 and the index of the last row is RowCount-1. When you add a new row, the RowCount increases, but the index of the last row is still RowCount-1.

So, when you are trying to use this:

Form3.StringGrid1.Cells[0,Form3.StringGrid1.RowCount] := 'Hoofdstad';

You are going out of bounds, because Form3.StringGrid1.RowCount is 1 too high. You need to use this instead:

Onderdelen := Form3.StringGrid1.RowCount;
Form3.StringGrid1.RowCount := Onderdelen + 1;
Form3.StringGrid1.Cells[0, Form3.StringGrid1.RowCount - 1] := 'Hoofdstad';

Alternatively, since Onderdelen already contains the proper index value:

Onderdelen := Form3.StringGrid1.RowCount;
Form3.StringGrid1.RowCount := Onderdelen + 1;
Form3.StringGrid1.Cells[0, Onderdelen] := 'Hoofdstad';