For...Next loop only works on initial step
VB beginner here. My For... Next Loop will not work and I cannot for the life of me figure out why. I have tried to display the results in a label and a text box with multiline enabled. Doesn't seem to matter. It's probably something obvious I have been overlooking for 2 hours. Thanks in advance for any help.
Option Explicit On
Option Strict On
Option Infer Off
Public Class Form1
Private Sub exitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub displayButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles displayButton.Click
Dim monthly As Double
开发者_运维百科 Dim results As Double
Dim interest As Double
''#clear textbox results
displayLabel.Text = String.Empty
monthlyTextBox.Text = String.Empty
''#calculate the monthly payment due
monthly = -Financial.Pmt(0.06 / 12, 12, 5000)
monthlyTextBox.Text = monthly.ToString("C2")
''#calculate the amounts applied to principal and interest
For per As Integer = 12 To 1 Step -1
results = -Financial.PPmt(0.06 / 12, per, 12, 5000)
interest = monthly - results
displayLabel.Text = results.ToString("C2") & " " & interest.ToString("C2") & ControlChars.NewLine
Next per
displayLabel.Focus()
End Sub
End Class
The problem is in two parts:
- Your code is running in the GUI thread - that is, the thread that your textbox or label control uses to repaint itself to the screen. This means the control can't redraw itself to show updated results until your entire method has finished.
- You write over the entire contents of the .Text property rather than append to it on each loop iteration.
Taken together, what you see when your code runs is the result of 12 iterations. It just happens to look very much like running one iteration.
In this case, I'm not sure problem 1 is a big deal. This is a quick enough operation and it looks like seeing all the results at once might be what you intend. Just be aware of the issue for the future. For item #2, I'd write the loop like this:
''#calculate the amounts applied to principal and interest
Dim resultText As New Text.StringBuilder()
For per As Integer = 12 To 1 Step -1
results = -Financial.PPmt(0.06 / 12, per, 12, 5000)
interest = monthly - results
resultText.AppendFormat("{0:C2} {1:C2}{2}", results, interest, Environment.NewLine)
Next per
displayLabel.Text = resultText.ToString()
We can improve upon this further by taking advantage of the format string to control spacing and make everything line up nice, rather than just inserting a couple spaces between terms. Try plugging this string into your .AppendFormat()
call:
{0,12:C2}{1:C2}{2}
You are reassigning displayLabel.Text each iteration you need to append to the .text field
精彩评论