ExtensionMethod.NET Home of 844 C#, Visual Basic, F# and Javascript extension methods


Validates that input text is a number


/// <summary>
/// Extension method to validate that input text is a number.
/// </summary>
/// <param name="e">Key Press Event Initialization.</param>
/// <param name="IsCalculation">if true then decimal point (.) is allowed, if false then decimal point (.) is not allowed</param>
public static void ValidateNumber(this TextBox txt, KeyPressEventArgs e, bool IsCalculation)
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
        if (e.KeyChar == '.' && IsCalculation)
            if (txt.Text.IndexOf('.') > -1)
                e.Handled = true;
            else e.Handled = false;
        else e.Handled = true;


private void txtRollNo_KeyPress(object sender, KeyPressEventArgs e)
    (sender as TextBox).ValidateNumber(e, false);

Author: Ahmer Sohail

Submitted on: 24 aug 2017

Language: C#

Type: System.Windows.Forms.TextBox

Views: 3078