Checking for numeric value entered in text box in Visual Basic
Asked Answered
T

6

5

I am working on a program for my Visual Basic class and have a quick question. One of the things we were encouraged to do was to check to make sure the quantity entered in a text box is actually a number. Our professor suggested using IsNumeric to perform this check, but I'm running into some trouble. I already had a good bit of the code written before he added this to the instructions, so not sure how to integrate this into the code I already have.

The main purpose of the program is to allow the user to add ingredients from one list box to the recipe list box, input a quantity for each selected ingredient in a text box, and calculate the total calories for the recipe. The way I have the code written now, IsNumeric is part of a nested if statement at the beginning of where I will start adding the selected ingredients to the recipe list box. I'm not sure if that's the correct place for it though.

Here is the code I have written so far.

Public Class Form1

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim i As Integer = lstIngredients.SelectedIndex
        Dim Quantity As Double
        Dim intCount As Integer = 0

        If Trim(txtQuantity.Text = "") Then
            Quantity = 1
        Else
            Quantity = Me.txtQuantity.Text
        End If

        If txtQuantity.Text Is IsNumeric() Then
            If intCount < Quantity Then
                lstRecipe.Items.Add(Quantity & " " & lstIngredients.Text)
                intCount += 1
            End If
        Else
            MessageBox.Show("The quantity entered is not numeric. Please add a numeric    quantity.")
        End If


    End Sub

    Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
        lstRecipe.Items.Clear()
        txtQuantity.Clear()
        txtAnswer.Clear()
    End Sub

    Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click


    End Sub
End Class

Also, here is the error I receive when I attempt to run this program as it is written.

Error   1   Argument not specified for parameter 'Expression' of 'Public   Function IsNumeric(Expression As Object) As Boolean'.    

Any suggestions would be greatly appreciated.

Transship answered 19/2, 2014 at 23:27 Comment(1)
possible duplicate of Checking to see if text box input is numericDeform
D
15

A more correct way to do that is to use the TryParse method available in the Int32 or Double class

If Double.TryParse(txtQuantity.Text, Quantity) Then
     If intCount < Quantity Then
         lstRecipe.Items.Add(Quantity & " " & lstIngredients.Text)
          intCount += 1
     End If
 Else
     MessageBox.Show("The quantity entered is not numeric. Please add a numeric    quantity.")
 End If

And you could also remove the code that test for the empty textbox.

The TryParse method wants two parameters, the first one is the string that could be converted, the second parameter is the variable that receives the result of the conversion if it is possible. If the conversion cannot be executed the function returns false.

There are numerous reasons to prefer Double.TryParse instead of IsNumeric.

The first reason is that with TryParse you also get the result of the conversion while with IsNumeric you would have to do the conversion after the check.

The second reason is that you could give to IsNumeric whatever object you want (also a Button for example) and it accepts it. You would never discover this kind of errors at compile time. Instead, with TryParse, you could only pass a string as its first parameter.

Dolf answered 19/2, 2014 at 23:30 Comment(3)
This is the preferred method (using .Parse or .TryParse) because IsNumeric is a VB holdover method that isn't all there. It can test for numeric formats, but it doesn't ensure that the value is completely numeric. For example, IsNumeric("$123") returns true but this obviously will cause an exception if you try to assign "$123" to a numeric variable... Without Parse methods, you'd have to do a character-by-character check. That may be preferred if you need to provide better feedback, such as checking a password for complexity, but for a basic numeric cast it is overkill.Armanda
@Armanda absolutely I agree.Dolf
+1 for best solution and don't using VB6 old methods like other answers.Scutiform
S
4

You're just using the function incorrectly - you need to pass the string as a parameter.

If IsNumeric(txtQuantity.Text) Then
Shepperd answered 19/2, 2014 at 23:30 Comment(0)
N
1

Use Regex.IsMatch:

Public Function isNumeric(input As String) As Boolean
    Return Regex.IsMatch(input.Trim, "\A-{0,1}[0-9.]*\Z")
End Function
Napery answered 28/2, 2016 at 23:30 Comment(0)
A
1

Yes, Double.Tryparse is the best answer to this question, but to save you time on coding and ensure that the value entered is always numeric, use the NumericDropdown control instead of the plain Text Box so that you are sure that inputted value is always numeric and save you time checking the inputted value since that control will not accept anything but numeric values only.

enter image description here

Arrival answered 29/5, 2020 at 5:49 Comment(0)
T
0

Use IsNumeric(txtQuantity.Text) if you have that method defined. Otherwise use Int32.TryParse() method. It will return true if the text passed in is a number.

Tadzhik answered 19/2, 2014 at 23:31 Comment(0)
C
0
Private Sub txbDwellTime_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbDwellTime.KeyPress

    numDecOnly(e)

End Sub


Public Sub numDecOnly(ByVal e As System.Windows.Forms.KeyPressEventArgs)
    If (Asc(e.KeyChar) >= 48 And Asc(e.KeyChar) <= 57 Or Asc(e.KeyChar) = 46) Then
        'good job do nothing we only allow positive Decimal numbers in this field
        'Asc(e.KeyChar) 48 Through 57 i.e. 0 through 9 Or Asc(e.KeyChar) 46 (dot= .)
    Else
        e.Handled = True
        MsgBox("Only Positive Decimal Numbers Allowed this field")
    End If

End Sub
Culminate answered 27/5, 2020 at 17:56 Comment(1)
Should't e be ByRef, as your setting e.Handled = True?Madeleinemadelena

© 2022 - 2024 — McMap. All rights reserved.