?
Solved

Restrict Textbox to Number and Decimal character only

Posted on 2009-12-17
12
Medium Priority
?
7,136 Views
Last Modified: 2013-11-08
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?

0
Comment
Question by:Mike_Stevens
  • 3
  • 2
  • 2
  • +5
12 Comments
 
LVL 15

Expert Comment

by:x77
ID: 26074646
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
 
LVL 15

Expert Comment

by:x77
ID: 26074668
Note.: The mask for a numeric value with a decimal is "N1", valid for all country languages (,.).
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 26075175
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
NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 26076238
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
 
LVL 27

Accepted Solution

by:
planocz earned 2000 total points
ID: 26077719
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
 
LVL 11

Expert Comment

by:ROMA CHAUHAN
ID: 26078300
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
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 26091068
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
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 26102937
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
 
LVL 12

Expert Comment

by:satsumo
ID: 27616055
None of these solutions will handle negative numbers.  The asker dosen't specify that the input number must be positive.
0
 
LVL 83

Expert Comment

by:CodeCruiser
ID: 27616118
>None of these solutions will handle negative numbers.
Never seen a negative Weight myself. If you have any examples, would love to see.
0
 
LVL 12

Expert Comment

by:satsumo
ID: 27617775
Hmm, me neither, didn't spot the weight part.  * facepalm *
0
 
LVL 5

Expert Comment

by:Tommy11b
ID: 28169374
Use the right tool for the right job, this is what the NumericUpDown control is for
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question