Hi everyone I am fairly new to programming VB. Net I have a program I have written to calculate the totals of snowfall for an each month and make it a yearly total for snow fall. Here is the code I currently have.

Public Class Form1


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        Dim a As Integer

        a = InputBox("Enter the snowfall totals month by month: ")

        ListBox1.Items.Add(a)

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

        Dim Total As Integer
        For Each Str As String In ListBox1.Items
            Total = Total + CInt(Str)
        Next
        TextBox1.Text = Total
    End Sub
End Class

I need for the program to check if the values are positive only and are not negative or non-numeric. Any help would be greatly appreciated. I know my syntax for variables isn't correct at the moment but I will be renaming variables once the program is fully functional.

Recommended Answers

All 3 Replies

To add only non negative values do this:

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim Total As Integer

        For Each Str As String In ListBox1.Items

            If CInt(Str) >= 0 Then
                Total = Total + CInt(Str)
            End If

        Next

        TextBox1.Text = Total

    End Sub

As your code stands at the moment it will fall over if you enter a non integer value anyway.

Okay thanks a bunch. What about if someone enters a a non-numeric value such as "a". Currently it crashes the program. I would like for it to display a message or something.

You'll want to get the value from the input box as a string as in

Dim a As String = InputBox("Enter the snowfall totals month by month: ")

Then you can test the string

If IsNumeric(a) Then
    num = CInt(a)

You may then test for positive or negative. Note that even if "a" is numeric, it may still contain a decimal point. You could always check for that as well.

However, there may be a better alternative. You could use a TextBox for input and set the textbox to accept only 0-9 as valid keystrokes. Here is an example

Private Sub TextBox1_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress

    Select Case e.KeyChar
        Case "0" To "9"         'allow digits
        Case vbBack             'allow backspace
        Case Else
            e.Handled = True    'ignore everything else
    End Select

End Sub

Note that left/right arrow and delete are also allowed. With the above code you'll only have to check for a null string (nothing entered).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.