Click here to Skip to main content
15,881,852 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Wish to use text box to only allow numeric Data entry

Can any one help me with code for restricting other than numbers and backspace in text box.
Posted
Updated 28-Mar-17 18:55pm
v3
Comments
walterhevedeich 9-Jun-11 4:27am    
Tag it. Windows forms or web application?
Ragi Gopi 9-Jun-11 4:28am    
Windows forms

You could use a MaskedTextBox[^] with a Mask of "####" - that is what it's there for...
 
Share this answer
 
On KeyPress event write following code

C#
if (char.IsNumber(e.KeyChar))
     e.Handled = false;
else
     e.Handled = true;
 
Share this answer
 
Comments
RakeshMeena 9-Jun-11 4:42am    
My 5! Though you don't need to put both If and else parts.
CS2011 9-Jun-11 4:47am    
Thanks.
Tarun.K.S 9-Jun-11 4:59am    
I beg to differ here, else *is* required.
CS2011 9-Jun-11 5:14am    
What Else ?? :-)
Tarun.K.S 9-Jun-11 5:28am    
Hahahhaaa! :D
 
Share this answer
 
You need a Masked textbox.

Here: Masked C# TextBox Control[^]

Further, you can also implement the functionality using OnKeyPress or OnKeyUp or OnBlur (there may be more events, pick any one that suits you). When the particular method event is raised, you can check for the key pressed or the text present/entered and act accordingly - show an alert/error/blankout.
 
Share this answer
 
C#
private void tbph_TextChanged_1(object sender, EventArgs e)
       {
           tbph.KeyPress += new KeyPressEventHandler(tbph_KeyPress);
       }
       private void tbph_KeyPress(object sender, KeyPressEventArgs e)
       {
           if ((e.KeyChar < '0') || (e.KeyChar > '9')) e.Handled = true;
       }



i tried above code ..
and got answer...
 
Share this answer
 
Comments
Tarun.K.S 9-Jun-11 5:15am    
How about copying a text, then pasting it( by right-clicking, then click paste on it). The text will appear.
Ragi Gopi 9-Jun-11 5:42am    
ohhhhh..thats a problem.....
Javascript Function:

C#
function isOnlyNumber(field) {
      var e = event;
      var charCode = e.which || e.keyCode;
      if (charCode > 47 && charCode < 58)
      {
      return true;
      }
      else{
      return false;
      }


Use This Function in TextBox onkeypress event as below.

<asp:TextBox ID="txt1" runat="server" CssClass="inputbox" onkeypress="return isOnlyNumber(this);"></asp:TextBox>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900