Search code examples
vb.netformsloopstextbox

Having trouble coding an application using a pretest do...loop in visual basic that displays a list of numbers


In my homework assignment, the user is given two text boxes in a form application to enter numbers. In the From box, the user will enter the first number they want to start with in the list. In the To box, they will enter the last number they want to show in the list.

For example:

From: 1 To: 5

List: 1 2 3 4 5

The assignment requires that I use a pretest do...loop to accomplish this. The problem is I can't figure out how to get the code to use numbers entered by the user.

Edit:

This is my current interface:

interface of application

I have already coded the For...Next loop. I will post that code below. I now have to complete the same concept as a pretest Do...Loop. I can't figure out how to get the loop to display the range of numbers specified by the user.

Code for For...Next:

Private Sub btnForNext_Click(sender As Object, e As EventArgs) Handles btnForNext.Click
    ' Display a list of numbers.

    Dim intFrom As Integer
    Dim intTo As Integer

    Integer.TryParse(txtFrom.Text, intFrom)
    Integer.TryParse(txtTo.Text, intTo)
    lstNumbers.Items.Clear()

    For intList As Integer = intFrom To intTo
        lstNumbers.Items.Add(intList)
    Next intList
End Sub

I have tried using Dim intList as Integer = intFrom To intTo but that gives me an end of statement expected error.


Solution

  • Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        'You get the input from the user exactly like you did for the For loop
        Dim intFrom As Integer
        Dim intTo As Integer
    
        Integer.TryParse(TextBox1.Text, intFrom)
        Integer.TryParse(TextBox2.Text, intTo)
        ListBox2.Items.Clear()
    
        'You want your do loop to keep looping While the intFrom is less than or Equal to intTo
        'The trick is to increment intFrom on every iteration or you will have an infinite loop
        Do While intFrom <= intTo
            ListBox2.Items.Add(intFrom)
            intFrom += 1
        Loop
        'Alternatively
        'Here you loop will continue Until intFrom is greater than intTo
        Do Until intFrom > intTo
            ListBox2.Items.Add(intFrom)
            intFrom += 1
        Loop
        'Both are pre-tests - choose one
    End Sub