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

2

How can you validate in TextBox when the user types letters instead of numbers a warning appears:

  

Only typing numbers in this field is allowed

With which function can I check?

    
asked by anonymous 18.04.2017 / 02:47

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, everything not is number and special navigation and editing keys I set the SuppressKeyPress property to% sup_to% suppress the preloaded key.

    
18.04.2017 / 04:24
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 the condition to also allow our decimal separator ','. If you want to allow only numbers, simply remove the last condition.

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

References:

  • What is Handled in C # arguments
  • KeyPressEventArgs.Handled Property
  • How to handle form-level keyboard input
  • Solution to ASP.Net

    Add a CompareValidator to your page and use the DataTypeCheck property and Type set as you want:

    ...
    Type="String|Integer|Double|Date|Currency"
    ...
    
    <asp:CompareValidator runat="server" Operator="DataTypeCheck" Type="Integer" 
     ControlToValidate="TextBox1" ErrorMessage="Só é permitido digitar números neste campo"/>
    
        
    18.04.2017 / 14:05