Search code examples
vb.netwinforms

Accept Integer Values but not text


Can I make it so that whenever I try typing a non-integer value into a text box, and press a button for an outcome, a message box will show saying that you need to type in an integer instead of the program crashing. I'm a new student who just started coding in school so I'd appreciate a basic explanation, thank you.

Public Class Form1
    Dim intempid As Integer
    Dim strname As String
    Dim dblsalary As Double
    Dim lbldisplay As String
    
    Private Sub btnconfirm_Click(sender As Object, e As EventArgs) Handles btnconfirm.Click
        intempid = txtid.Text
        strname = txtname.Text
        dblsalary = txtsalary.Text
        lbldisplay = lblans.Text

        Dim dblNI As Double
        dblNI = dblsalary * 0.1
        lblans.Text = dblNI

        If intempid = Integer Then
            MessageBox.Show("Error: please type your number ID") 'this i what I'm struggling with
        End If

        lblans.Text = "welcome " & strname & ", you're national insurance is: " & dblNI

    End Sub
End Class

Solution

  • The problem is the very first line of the method:

    intempid = txtid.Text
    

    You can't assign a string to an integer.


    If this compiles at all, you should turn on Option Strict. This will add a number of new errors, making it seem like it's giving you more work. The opposite is true: every one of these errors is there in your code whether or not you have Option Strict turned on: the option merely helps you find them, and find them faster, so you can finish more quickly. So take the time to resolve the compiler errors.

    As an example, here's the quick/naive resolution for that line

    intempid = Interger.Parse(txtid.Text)
    

    But we can do better. This will still cause a problem if the text isn't a valid integer. So we actually want something more like this:

    If Not Integer.TryParse(intempid, txtid.Text) Then
         MessageBox.Show("Error: please type your number ID") 
    End If
    

    But we can still do better. Since this textbox should only have numbers, you can use an input mask or a dedicated numeric input control (there are a number of options out there) to help the user get the input right in the first place.


    Finally, I'll add that type prefixes like int and str, which were invented at Microsoft for VB and C++, made sense back in the old vb6 world, with older tooling and for a platform more native to dynamic types. But since .NET, type prefixes are not recommended (except for winforms controls themselves, so lbl is fine for the label, and txt is fine for the textboxes). Microsoft's own style guidelines for the language now explicitly state, "Do not use Hungarian notation".

    So instead of intempid, you should have EmpID.