Reputation: 21
How can I get the results to show each year and the year end value for each year?
double investment_decimal = Double.Parse(txtAmount.Text);
double rate_decimal = Double.Parse(txtRate.Text);
double years = Double.Parse(txtSlideValue.Text);
years = Convert.ToDouble(txtSlideValue.Text);
double calculation = 0;
//for loop
for (int i = 1; i < years + 1 ; i++)
{
calculation = investment_decimal * Math.Pow((1 + rate_decimal / years), (i));
txtCalculation.Text = Convert.ToString("Year " + i.ToString() +"\t" + "Year End Value " + calculation.ToString("C")).PadRight(10);
}
Upvotes: 2
Views: 243
Reputation: 726489
Your code makes multiple assignments to a UI element's text before letting UI refresh. That is why only the last item remains visible; the rest of them get overwritten as you go through the loop.
You should prepare a string that corresponds to the entire string in the text box, and put it into txtCalculation.Text
all at once:
StringBuilder sb = new StringBuilder();
for (int i = 1; i < years + 1 ; i++)
{
calculation = investment_decimal * Math.Pow((1 + rate_decimal / years), (i));
sb.AppendFormat("Year {0}\tYear End Value {1:C}\n", i, calculation);
}
txtCalculation.Text = sb.ToString();
Note the use of AppendFormat
in place of string concatenation operator +=
with multiple values. If you want to make a string, rather than appending to StringBuffer
, you could use string.Format
or interpolated strings of C# 6.
Upvotes: 2