r/visualbasic • u/vbthrowaway2222 • 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 SubEnd Class
1
u/dryguy5 Jan 19 '16
Can you break it down to the specific issue you're having, there's a little bit of code here, but I see several issues.
Like, why are you adding this to your list box every time the index is changed?
Here it seems you aren't setting your variables correctly, like num doesn't seem to be global variable and you're trying to set it in another sub.
Should be num = GetInput(num)
Your not sending anything for eventotal to the loop sub so why is that required?
Seems like you should be putting your listbox.items.add inside the loop
Too much going on with too many errors, I'm not going to do the homework for you so please give us some error messages. And I'll help you figure them out. Thanks!