Rivka
Rivka

Reputation: 2202

Winforms TextBox - Allow numeric or 1 decimal place only

How can I prevent users from entering anything other than a numeric value or a decimal value with 1 decimal place?

The user should be allowed to enter any length of characters (if decimal value, before the decimal).

Upvotes: 1

Views: 3451

Answers (3)

Ken Yannitell
Ken Yannitell

Reputation: 1

Maybe a little late to the party on this one, but I extended a simple textbox to force the entry to always be formatted decimal.. Simple but effective

Imports System.Runtime.InteropServices
Imports System.Drawing.Imaging
Imports System.ComponentModel
Imports System.Text.RegularExpressions


<ToolboxBitmap(GetType(System.Windows.Forms.TextBox))> _
Public Class NumericTextBox
    Inherits TextBox

    Dim _TextBoxValue As String
    Dim _CaretPosition As Integer

    Protected Overrides Sub OnKeyDown(e As KeyEventArgs)
        MyBase.OnKeyDown(e)
        _TextBoxValue = Me.Text
        _CaretPosition = Me.SelectionStart
    End Sub
    Protected Overrides Sub OnKeyUp(e As KeyEventArgs)
        MyBase.OnKeyUp(e)

        If (Me.Text.Length = 0) Or (Me.Text = _TextBoxValue) Then Exit Sub
        If IsNumeric(Me.Text) Then

            If Me.Text.EndsWith(".") Then
                Me.Text = Convert.ToDecimal(Me.Text) & "."
            Else
                Me.Text = Convert.ToDecimal(Me.Text)
            End If

        Else
            Me.Text = _TextBoxValue
        End If
        Me.SelectionStart = _CaretPosition + 1
    End Sub
End Class

Upvotes: 0

Gnanagurusamy
Gnanagurusamy

Reputation: 1

Regex match = new Regex(@"^[1-9]\d*(.\d{1})?$"); Working Correctly

Upvotes: -1

Alex
Alex

Reputation: 8116

Try using Regex. This pattern should work: Regex match = new Regex(@"^[1-9]\d*(\.\d{1})?$"), put that in your validating event of the textbox. If its no match, Undo() or delete the Textbox.Text property.

    Regex match = new Regex(@"^[1-9]\d*(\.\d{1})?$");

    private void textBox1_Validating(object sender, CancelEventArgs e)
    {
        if (!match.IsMatch(textBox1.Text))
        {
            textBox1.Undo(); 
        }
    }

To actually undo the input immediatly, you have to use

    private void textBox1_KeyUp(object sender, KeyEventArgs e)
    {
        if (!match.IsMatch(textBox1.Text))
        {
            textBox1.Undo();
        }
    }

Because if you use KeyDown, the TextBox has no Undo State.

2nd Edit: If you want both cases to match, you have to do the check in the Validating Event or a similar one. Since the regex uses "$" to make sure, no characters are added in the end, you cannot enter "." or else you'd end up having a number like 1. which would require additional checking.

Upvotes: 3

Related Questions