Validate Textbox to allow only Number and Decimal based on CultureInfo.CurrentCulture

Validate Textbox to allow only Number and Decimal based on CultureInfo.CurrentCulture

This blog post is related to Validate Textbox to allow only Number and Decimal based on CultureInfo.CurrentCulture using VB.NET and C#.

Related Question: How to validate textbox in windows form application to allow only number and decimal?

VB.NET code to Validate Textbox to allow only Number and Decimal based on CultureInfo.CurrentCulture

Support you have textbox named TextBox1. You can validate number and decimal point on keypress event

The complete code

Textbox Event

Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
	Dim isNumber = isNumber(e.KeyChar, CType(sender, TextBox).Text)
            If (isNumber) Then
                e.Handled = False
            Else
                MessageBox.Show("Enter a valid numeric value")
                e.KeyChar = ""
            End If
End Sub

isNumber Method to validate Number and Decimal in VB.NET

Private Function isNumber(ByVal ch As Char, ByVal text As String) As Boolean
        Dim result As Boolean = True
        Dim decimalChar As Char = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator)

        If ch = decimalChar AndAlso text.IndexOf(decimalChar) <> -1 Then
            result = False
            Return result
        End If

        If Not Char.IsDigit(ch) AndAlso ch <> decimalChar AndAlso Asc(ch) <> Keys.Back Then result = False
        Return result
End Function

Similar like VB.NET you can also implement the same logic in C#

C# code to Validate Textbox to allow only Number and Decimal based on CultureInfo.CurrentCulture

Textbox Event

private void TextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    var isNumber = isNumber(e.KeyChar, (TextBox)sender.Text);
    if (isNumber)
        e.Handled = false;
    else
    {
        MessageBox.Show("Enter a valid numeric value");
        e.KeyChar = "";
    }
}

isNumber Method to validate Number and Decimal in C#

public bool isNumber(char ch, string text)
{
    bool result = true;
    char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);

    //check only one decimal separator
    if (ch == decimalChar && text.IndexOf(decimalChar) != -1)
    {
        result = false;
        return result;
    }

    //check if it is a digit, decimal separator and backspace
    if (!Char.IsDigit(ch) && ch != decimalChar && ch != (char)Keys.Back)
        result = false;

    return result;
}

Hope the above code helps you. Happy coding!