Search code examples
vb.nettextboxintegerrestriction

How to restrict user only being able to enter integer in textbox in vb.net


When user wants to calculate their BMI, how do I restrict them so they can only enter integer in the textbox when the program loads?

Also if possible how can I turn the BMI answer into 2 or 1 decimal place?

CODE:

Public Class Form1

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

        txtHeight.Text = txtHeight.Text / 100 ' converts txtheight into meter

        lblBMI.Text = txtWeight.Text / txtHeight.Text ^ 2 'BMI is equal to txtweight divided by (txtheight)^2

        'BMI = x KG / (y M * y M)

    End Sub

End Class

Thats the Design

enter image description here

I know its probably very simple but I'm fairly new to programming, Thank you!


Solution

  • Refer here.

     Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
    
        '97 - 122 = Ascii codes for simple letters
        '65 - 90  = Ascii codes for capital letters
        '48 - 57  = Ascii codes for numbers
    
        If Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
                e.Handled = True
            End If
        End If
    
    End Sub
    

    Formatting number into Decimal places:

    YourLabel.Text = FormatNumber(YourNumber,N) 'N = Number of Decimal Places