Posted by Joey p12386 on May 15, 2007
In Reply to Adding stringgrid values posted by Sarah-Jayne on
May 12, 2007
: This is probably a very simple question for you, but I am very new to Delphi!
: 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.
:
Help would be very much appreciated!!!
: Thanks a bunch, Sarah-Jayne.
Hi there,
Here is the code that should solve the problem.
StringGrid1.Cells[4,1] := IntToStr( StrToInt( StringGrid1.Cells[1,1] ) + StrToInt( StringGrid1.Cells[2,1] ) + StrToInt( StringGrid1.Cells[3,1] ) );
You should just note that StrToInt isn't a very great function as 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 your user types 'Bob' instead of a number it will return the string for '0 or any other integer you give for the second value.
Hope this helps ^_^
Joey
Related articles
StrToInt or StrToIntDef ? StrToInt (string-to-integer) causes an error for "invalid" strings. How to avoid this? |
Follow Ups