[c#] C# Numeric Only TextBox Control

I am using C#.NET 3.5, and I have a problem in my project. In C# Windows Application, I want to make a textbox to accept only numbers. If user try to enter characters message should be appear like "please enter numbers only", and in another textbox it has to accept valid email id message should appear when it is invalid. It has to show invalid user id.

This question is related to c# textbox .net-3.5

The answer is


I think it will help you

<script type="text/javascript">
function isNumberKey(evt) {
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 32 && (charCode < 48 || charCode > 57) && (charCode != 45) && (charCode != 43) && (charCode != 40) && (charCode != 41))
        return false;

    return true;
}


I used the TryParse that @fjdumont mentioned but in the validating event instead.

private void Number_Validating(object sender, CancelEventArgs e) {
    int val;
    TextBox tb = sender as TextBox;
    if (!int.TryParse(tb.Text, out val)) {
        MessageBox.Show(tb.Tag +  " must be numeric.");
        tb.Undo();
        e.Cancel = true;
    }
}

I attached this to two different text boxes with in my form initializing code.

    public Form1() {
        InitializeComponent();
        textBox1.Validating+=new CancelEventHandler(Number_Validating);
        textBox2.Validating+=new CancelEventHandler(Number_Validating);
    }

I also added the tb.Undo() to back out invalid changes.



use this code:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
        }

this way is right with me:

private void textboxNumberic_KeyPress(object sender, KeyPressEventArgs e)
{
     const char Delete = (char)8;
     e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}

You can check the Ascii value by e.keychar on KeyPress event of TextBox.

By checking the AscII value you can check for number or character.

Similarly you can write logic to check the Email ID.


From C#3.5 I assume you're using WPF.

Just make a two-way data binding from an integer property to your text-box. WPF will show the validation error for you automatically.

For the email case, make a two-way data binding from a string property that does Regexp validation in the setter and throw an Exception upon validation error.

Look up Binding on MSDN.


try
{
    int temp=Convert.ToInt32(TextBox1.Text);
}
catch(Exception h)
{
    MessageBox.Show("Please provide number only");
}

TRY THIS CODE

// Boolean flag used to determine when a character other than a number is entered.
private bool nonNumberEntered = false;
// Handle the KeyDown event to determine the type of character entered into the control.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    // Initialize the flag to false.
    nonNumberEntered = false;
    // Determine whether the keystroke is a number from the top of the keyboard.
    if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
    {
        // Determine whether the keystroke is a number from the keypad.
        if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9)
        {
            // Determine whether the keystroke is a backspace.
            if (e.KeyCode != Keys.Back)
            {
                // A non-numerical keystroke was pressed.
                // Set the flag to true and evaluate in KeyPress event.
                nonNumberEntered = true;
            }
        }
    }
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (nonNumberEntered == true)
    {
       MessageBox.Show("Please enter number only..."); 
       e.Handled = true;
    }
}


Source is http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=VS.90).aspx


You might want to try int.TryParse(string, out int) in the KeyPress(object, KeyPressEventArgs) event to check for numeric values. For the other problem you could use regular expressions instead.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to textbox

Add two numbers and display result in textbox with Javascript How to check if a text field is empty or not in swift Setting cursor at the end of any text of a textbox Press enter in textbox to and execute button command javascript getting my textbox to display a variable How can I set focus on an element in an HTML form using JavaScript? jQuery textbox change event doesn't fire until textbox loses focus? PHP: get the value of TEXTBOX then pass it to a VARIABLE How to clear a textbox once a button is clicked in WPF? Get current cursor position in a textbox

Examples related to .net-3.5

Get first element from a dictionary redistributable offline .NET Framework 3.5 installer for Windows 8 How to read an entire file to a string using C#? HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.) Change the Textbox height? How to get current date in 'YYYY-MM-DD' format in ASP.NET? C# Numeric Only TextBox Control Will the IE9 WebBrowser Control Support all of IE9's features, including SVG? Use LINQ to get items in one List<>, that are not in another List<> Get Absolute URL from Relative path (refactored method)