Adding stringgrid values

Question

I have a series of values within a stringgrid, in cells [1,1], [2,1] and [3,1]. I want to add these together to calculate the total value within these cells, and display this in cell [4,1]. I have tried various IntToStr, StrToInt combinations but as of yet have failed, instead of calculating the total values, the values are simply put together e.g. 1+2+3 = 123 instead of the correct answer of 6.

Answer

Try the following code:

StringGrid1.Cells[4,1] :=
IntToStr( StrToInt( StringGrid1.Cells[1,1] ) + StrToInt( StringGrid1.Cells[2,1] ) + StrToInt( StringGrid1.Cells[3,1] ) );

Note: with StrToInt, if there is any input other that characters 0 - 9 then an error will be thrown. You could use StrToIntDef which is the same but uses a default value if the input is invalid.

StringGrid1.Cells[4,1] :=
IntToStr( StrToIntDef( StringGrid1.Cells[1,1], 0 ) + StrToIntDef( StringGrid1.Cells[2,1], 0 ) + StrToIntDef( StringGrid1.Cells[3,1], 0 ) );

So if the user types 'Bob' instead of a number it will return the string for 0 or any other integer you give for the second value.


Members of the DelphiLand Club can access the full version of our tutorials, including all fully commented source code files.

Click here to become a DelphiLand Club member.