Reputation:
I have a StringGrid that looks like this:
+----------+----------+----------+----------+----------+
| FixedRow | FixedRow | FixedRow | FixedRow | FixedRow |
+----------+----------+----------+----------+----------+
| Data | Data | Data | 100 | Data |
+----------+----------+----------+----------+----------+
| Data | Data | Data | 158 | Data |
+----------+----------+----------+----------+----------+
| Data | Data | Data | 1002 | Data |
+----------+----------+----------+----------+----------+
The StringGrid can have any number of rows and I want to, within a Timer's tick event, find the value of each cell in column 4 and decrease its value by 1.
How can I read and manipulate a TStringGrid in this way?
Upvotes: 0
Views: 2311
Reputation: 109158
This is very straightforward.
Simply iterate over the data (non-header) rows, and for each row, obtain the value in the fourth column, convert it to an integer, decrease it, convert it back to a string, and set the cell's value to this string.
Since you have no fixed column, all columns are data columns. They are indexed 0, 1, 2, 3, 4, the fourth thus having index 3.
Since you have a fixed (header) row, the rows are indexed 0, 1, 2, ..., N − 1, with the data rows being 1, 2, ..., N − 1.
procedure TForm1.Timer1Timer(Sender: TObject);
var
y: Integer;
Val: Integer;
begin
for y := 1 to StringGrid1.RowCount - 1 do
begin
Val := StrToInt(StringGrid1.Cells[3, y]);
Dec(Val);
StringGrid1.Cells[3, y] := Val.ToString;
end;
end;
Upvotes: 4