Restrict Textbox to Number and Decimal character only

I have a textbox on a windows form in a vb.net project I am working on in visual studio.   The value to be stored in the text box is a weight.   How can i restrict the user so that they can only enter numbers and a decimal point in the box?

Mike_StevensAsked:
Who is Participating?
 
planoczCommented:
simple textbox code...........
    Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        Dim KeyAscii As Short = Asc(e.KeyChar)
        ' Check if the typed character is a letter.
        If Char.IsDigit(e.KeyChar) = False And _
         Char.IsControl(e.KeyChar) = False Then
            e.Handled = True
        End If
        ' Check if the typed character is a period.
        If KeyAscii = 46 Then
            e.Handled = False
        End If
    End Sub

Open in new window

0
 
x77Commented:
You can use MaskEditBox.
Limit chars by KeyPress, is more complex.
You can also Bind the textbox to a numeric Property or any other DataSource, then Binding.validation controls correct data value for a Mask Format.
0
 
x77Commented:
Note.: The mask for a numeric value with a decimal is "N1", valid for all country languages (,.).
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Éric MoreauSenior .Net ConsultantCommented:
I hate the MaskedTextbox

I prefer to use a NumericUpDown control or a custom control (check http://www.emoreau.com/Entries/Articles/2003/03/Creating-your-own-Windows-Custom-Control.aspx)
0
 
käµfm³d 👽Commented:
You could use a RegEx to verify the input. In the following, I limited the input to being any number of digits followed by optional

    1. one decimal point
    2. between 1 and 2 digits

If you wanted to alter the minimum and maximum number of digits, change the {1, 2} part--where 1 corresponds to the minimum number and 2 corresponds to the maximum number.

I also added a ErrorProvider component to my test form for visual feedback to the user. You can, of course, inform the user how you like.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim text As String = Me.TextBox1.Text.Trim()

        If text.Length = 0 OrElse Not System.Text.RegularExpressions.Regex.IsMatch(text, "^\d*(?:\.\d{1,2})?$") Then
            Me.ErrorProvider1.SetError(Me.TextBox1, "Please enter a value which contains only numbers and at most two decimal places!")
        Else
            Me.ErrorProvider1.SetError(Me.TextBox1, String.Empty)
        End If

    End Sub

Open in new window

0
 
ROMA CHAUHANProject LeadCommented:
Private Sub TextBox2_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
        If IsNonNumericEntered(sender, Asc(e.KeyChar)) = False Then
            e.Handled = True
        End If
    End Sub

    Function IsNonNumericEntered(ByVal txtPassedTextBox As TextBox, ByVal txtAscVal As Integer) As Boolean
        'If textbox already contains . then don't allow to enter it again
        If txtAscVal = 46 And txtPassedTextBox.Text.Contains(".") Then
            Return False
        ElseIf (txtAscVal >= 46 And txtAscVal <= 57) Or txtAscVal = 8 Then
            Return True
        End If
        Return False
    End Function
0
 
CodeCruiserCommented:
I use following code in my project which only allows numbers, one decimal point, and two digits after decimal point.

You can replace this line
Dim txt As DevExpress.XtraEditors.TextEdit = CType(sender, DevExpress.XtraEditors.TextEdit)

with
Dim txt as TextBox = Ctype(Sender, TextBox)
        Dim txt As DevExpress.XtraEditors.TextEdit = CType(sender, DevExpress.XtraEditors.TextEdit)
        If Asc(e.KeyChar) = 39 Then
            e.Handled = True
        End If
        If Asc(e.KeyChar) = 32 Then
            If txt.Text.Length = 0 Then
                e.Handled = True
            End If
        End If
        If Asc(e.KeyChar) = 46 Then
            If txt.Text.Contains(".") Then
                e.Handled = True
            End If
            If txt.Text.Length = 0 Then
                e.Handled = True
            End If
        End If
        If Asc(e.KeyChar) <> 46 And Asc(e.KeyChar) <> 8 Then
            If Asc(e.KeyChar) = 3 Or Asc(e.KeyChar) = 22 Then
                e.Handled = True
            End If
            If Char.IsDigit(e.KeyChar) = False And Char.IsControl(e.KeyChar) = False Then
                e.Handled = True
            End If
            If txt.Text.Contains(".") Then
                If txt.Text.Split(".")(1).Length = 2 Then
                    e.Handled = True
                End If
            End If
        End If
    End Sub

Open in new window

0
 
CodeCruiserCommented:
The selected solution wont limit the number of periods(.) in the textbox. So the user could type a weight like "123.321.123" which does not look like a weight does it?
0
 
satsumoSoftware DeveloperCommented:
None of these solutions will handle negative numbers.  The asker dosen't specify that the input number must be positive.
0
 
CodeCruiserCommented:
>None of these solutions will handle negative numbers.
Never seen a negative Weight myself. If you have any examples, would love to see.
0
 
satsumoSoftware DeveloperCommented:
Hmm, me neither, didn't spot the weight part.  * facepalm *
0
 
Tommy11bCommented:
Use the right tool for the right job, this is what the NumericUpDown control is for
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.