How can I detect if the value of a textbox has letters?

Asked

Viewed 427 times

2

How it is possible to validate in a TextBox when the user type letters instead of numbers appear a warning:

is only allowed to enter numbers in this field

What function can I check with?

  • 1

    Web or Desktop?

  • A Javascript function would help you?

2 answers

2

You can use the code

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
    e.SuppressKeyPress = !((e.KeyCode >= Keys.D0 && e.KeyCode <= Keys.D9) || (e.KeyCode >= Keys.NumPad0 && e.KeyCode <= Keys.NumPad9) ||
        (e.KeyCode == Keys.Tab || e.KeyCode == Keys.Back || e.KeyCode == Keys.Capital || e.KeyCode == Keys.CapsLock || e.KeyCode == Keys.Enter ||
        e.KeyCode == Keys.Insert || e.KeyCode == Keys.Home || e.KeyCode == Keys.Delete || e.KeyCode == Keys.End || (e.KeyCode >= Keys.Left && e.KeyCode <= Keys.Down)));

    if (e.SuppressKeyPress)
        MessageBox.Show("só é permitido digitar números neste campo");

}

In this code, all that nay for number and special navigation and editing keys I select the property SuppressKeyPress with true to delete the down button.

1

A very simple solution - Winforms

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != ',')) {
        e.Handled = true;
    }

    if (e.Handled)
        MessageBox.Show("Só é permitido digitar números neste campo");
}

Note that I added in condition to allow also our decimal separator , . If you want to allow only numbers, just withdraw the last condition.

if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar)) {
    e.Handled = true;
}

References:

  1. What is Handled for C arguments#
  2. Property Keypresseventargs.Handled
  3. How to manipulate keyboard input at form level

Solution for ASP.Net

Add on your page one CompareValidator and use the property DataTypeCheck and in the Type define as you wish:

...
Type="String|Integer|Double|Date|Currency"
...

<asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer" 
 ControlToValidate="TextBox1" ErrorMessage="Só é permitido digitar números neste campo"/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.