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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Praveen KumarRank #4 · 79.9K reputationPosted Dec 13, 2012, 9:17 PM EST
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
Satyapriya NayakRank #47 · 31.5K reputationPosted Dec 13, 2012, 11:06 PM EST
venkata kumarRank #5,034 · 314 reputationPosted Dec 13, 2012, 11:40 PM EST
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;
}
}
Shankar MRank #874 · 2.5K reputationPosted Dec 14, 2012, 12:28 AM EST
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.