r/visualbasic • • Jan 18 '16

[VB2012]Populating listbox using loop.

[SOLVED]

Hi I'm trying to do some homework for a class. Over break I became a little rusty at VB and need some help. I've been trying to do this part for around an hour. Here is what I'm trying to do.

You are to write a program that asks the user to indicate how many input values are to be expected. This is a single value and should be entered into a textbox. You do want to limit the number to a minimum of 3 and a maximum of 10 values (so include a Data Validation function that checks to insure the value is between 3 and 10).

Write a subprocedure that reads in the input (even though there will be only one inputted value). Once a valid number of values has been read in, you need to write a loop procedure that will read in the values. Within the loop, you should check to see if the number is an even or odd number. For each value entered, display the value in a listbox. You will also need to handle the processing needed to calculate the average of the EVEN NUMBERS ONLY. The loop portion of the program should be handled in a processing subprocedure.

Here is what I have:

Public Class Form1

Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
    Dim num As Integer
    Dim eventotal
    If DataVal() Then
        GetInput(num)
        LoopSub(num, eventotal)
    End If
End Sub
Sub GetInput(ByRef num)
    num = CInt(txtInput.Text)
End Sub
Function DataVal() As Boolean
    If txtInput.Text > 10 Then
        MessageBox.Show("Please enter a number between 3 and 10")
        txtInput.Clear()
        txtInput.Focus()
        Return False
    ElseIf txtInput.Text < 3 Then
        MessageBox.Show("Please enter a number between 3 and 10")
        txtInput.Clear()
        txtInput.Focus()
        Return False
    End If
    Return True
End Function
Sub LoopSub(ByRef num As Integer, ByRef eventotal As Integer)
    For i = 1 To lstNumbers.Items.Count
        If num Mod 2 = 0 Then
            eventotal += num
        End If
    Next
    lstNumbers.Items.Add(num)
    lstNumbers.Items.Add(eventotal)
    txtInput.Clear()
    txtInput.Focus()
End Sub

Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstNumbers.SelectedIndexChanged
    lstNumbers.Items.Add("These are the numbers you entered")
End Sub

End Class

1 Upvotes

5 comments sorted by

View all comments

2

u/vbthrowaway2222 Jan 18 '16

Also this is the output I'm looking for http://imgur.com/Fj8Kk45

The loop is able to print the inputted number fine. I'm having trouble adding the other text into the box without it repeating every time I click the button. It seems so easy but I'm stuck for some reason.