Help with For loop and label

dumwalke

New member
Joined
Sep 10, 2009
Messages
3
Programming Experience
Beginner
Hello,

I am new to VB programming. I have the following code. When I execute my program only the last value from the loop is displayed in the label. I do write my code so that all of the values (years 1 to 5) show up in the label?

Any help would be greatly appreciated!

For y = 1 To 5
dblFV1 = FV(dblRate / 12, y * 12, -dblMthAmtDbl)
lblResult.Text = ("Future value at end of ..." & vbCrLf & "Year " & y & ": " & FormatCurrency(dblFV1, 2))
Next y
 
the reason it's only showing the last value is because in the loop you're only setting the label to the current value instead of concatenating the values as you go, IE you're doing this:
VB.NET:
lblResult.Text =
When you should be doing this:
VB.NET:
lblResult.Text &=

But in a case like this, wouldn't it make more sense to use a ListView (set to DetailView) and you just add a ListView item to it as the loop goes? That way it doesn't matter how big the loop is, it just keeps adding the data.
 
Thanks for the tip on concatenating. This worked great except that now my results look like this:

Future value at the end of ...
Year 1:$1,841.83Future value at the end of ...
Year 2:$3,777.89Future value at the end of ...

It is also concatenating the "Future value at the end of ..." text to the end of each line. How would I code this so that this text only shows up one time at the top?

Thanks so much!
 
It's because you have that in the loop itself...
VB.NET:
lblResult.Text = "Future value at end of ..."
For y = 1 To 5
    dblFV1 = FV(dblRate / 12, y * 12, -dblMthAmtDbl)
    lblResult.Text &= Environment.NewLine & "Year " & y & ": " & dblFV1.ToString("c")
Next y
Ideally one would use a StringBuilder for this:
VB.NET:
Dim str As New System.Text.StringBuilder
str.Append("Future value at end of ...")
For y = 1 To 5
    str.Append(Environment.NewLine & "Year " & y & ": " & FV(dblRate / 12, y * 12, -dblMthAmtDbl).ToString("c"))
Next y
lblResult.Text = str.ToString()
 
Back
Top