简体   繁体   中英

TextBox.Text accept decimal inputs only

How to make txtamount.text accept only decimal values,it should accept only one . not more than one.

My following is my try but it accept more .

Private Sub txtamount_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtamount.KeyPress
        If Asc(e.KeyChar) <> 8 Then
            If (Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57) And Asc(e.KeyChar) <> 46 Then
                e.Handled = True
            End If
        End If
    End Sub

You can use

        Dim asccode As Integer = Asc(e.KeyChar)
        If asccode <> 8 Then
            If asccode = 46 And txtPackageAmount.Text.Contains(".") Then
                e.Handled = True
            End If
            If (asccode < 48 Or asccode > 57) And asccode <> 46 Then
                e.Handled = True
            End If
        End If

I recommend using a NumericUpDown instead. That has a property called DecimalPlaces where you can set the limit of how many decimals the user can enter. Then you would not need any code just to validate only 1 "." is entered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM