Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Basic Loop and Display one line at a time

I'm using visual studios 2008, VB9 and I am trying to write an app that basically performs calculations on a set of data input by a user. During the calculations, I want to display the data at each step, and have it retained in the display area on the GUI (not overwritten by the next data being displayed).

For example:

UserInput = 1

Do

  UserInput += 1

  OutputLabel.Text = "UserInput " & UserInput

Loop Until UserInput = 5

and the output would look like

UserInput 1 UserInput 2 UserInput 3 UserInput 4 UserInput 5

I tried this, and other loop structures and can't seem to get things right. The actual app is a bit more sophisticated, but the example serves well for logical purposes.

Any tips are welcome, thanks!

like image 964
Jmichelsen Avatar asked Jan 20 '10 04:01

Jmichelsen


People also ask

What are the 3 types of loops in Visual Basic?

Visual Basic has three main types of loops: for.. next loops, do loops and while loops.

How do you write a loop in Visual Basic?

In VB.NET, when we write one For loop inside the body of another For Next loop, it is called Nested For Next loop. Syntax: For variable_name As [Data Type] = start To end [ Step step ] For variable_name As [Data Type] = start To end [ Step step ]

What is indeterminate loop in VB?

Indeterminate loops run for an unknown number of repetitions until a condition is true or while a condition is true. Four types of indeterminate loops. Until loop with termination condition before body of loop. While loop with termination condition before body of loop.


2 Answers

This is the simple version:

Dim delimiter as String = ""
For UserInput As Integer = 1 To 5
    OutputLabel.Text &= String.Format("{0}UserInput {1}", delimiter, UserInput)
    delimiter = " "
Next

However, there are two problems with it and others like it (including every other answer given so far):

  1. It creates a lot of extra strings
  2. Since it's in a loop the label won't be able to process any paint events to update itself until you finish all of your processing.

So you may as well just do this:

Dim sb As New StringBuilder()
Dim delimiter As String = ""
For UserInput As Integer = 1 To 5
    sb.AppendFormat("{0}UserInput {1}", delimiter, UserInput)
    delimiter = " "
Next
OutputLabel.Text = sb.ToString()

And if you really want to have fun you can just do something like this (no loop required!):

OutputLabel.Text = Enumerable.Range(1, 5).Aggregate(Of String)("", Function(s, i) s & String.Format("UserInput {0} ", i))
like image 166
Joel Coehoorn Avatar answered Sep 28 '22 23:09

Joel Coehoorn


You need to concatenate the value in OutputLabel.Text.

OutputLabel.Text &= "UserInput " & UserInput

You might also want to reset it before the loop: OutputLabel.Text = ""

like image 36
Ahmad Mageed Avatar answered Sep 28 '22 23:09

Ahmad Mageed