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?
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?
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.
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:
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"/>