How to allow users to enter only numbers to a text box
am working with windows application and there is no validator controls
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Shankar MPosted Dec 14, 2012, 5:28 AM
You can also control entering the numeric values in the text box using the below key press event for code:
Text Box Key Press Event :
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
{
e.Handled = true;
}
To allow back space we have excluded the character code 8 BackSpace key. The numeric values for Key code lies between 48 and 57 so by this we exclude the characters when type using e.Handled = true.
venkata kumarPosted Dec 14, 2012, 4:40 AM
u can add fallowing code in which ever control u want to allow number for that textbox keypress event u can implement it.
private void textbox1_KeyPress(object sender, KeyPressEventArgs e)
{
try
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
MessageBox.Show("Enter Numbers Only", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
}
catch (Exception ex)
{
throw ex;
}
}
Satyapriya NayakPosted Dec 14, 2012, 4:06 AM
Praveen KumarPosted Dec 14, 2012, 2:17 AM
we have so many way's to achieve it: Example
<asp:TextBox ID="TextBox1" runat="server">asp:TextBox>
ControlToValidate="TextBox1"
ValidationExpression="\d+"
Display="Static"
EnableClientScript="true"
ErrorMessage="Please enter numbers only"
runat="server"/>
Thanks