Click here to Skip to main content
15,881,859 members
Please Sign up or sign in to vote.
3.67/5 (2 votes)
See more:
Hello, I want allow only to enter Integer value in a textbox with no decimals/points/dot in C#. Till now I did this far. Can someone assist me on this. would be a great help. Now I just need to prevent the decimal part.

C#
private void Quantity_txt_KeyPress(object sender, KeyPressEventArgs e)
        {
            char ch = e.KeyChar;
            if (!Char.IsDigit(ch) && ch != 8 && ch != 46) 
            {
                e.Handled = true;
            }
        }
Posted

So stop allowing it through: remove the && ch != 46 part which allows '.'
 
Share this answer
 
Comments
[no name] 14-May-14 6:43am    
Thanks Man. It worked.
OriginalGriff 14-May-14 6:58am    
You're welcome!
You could use a NumericUpDown control assuming this is a Windows Forms based application.
 
Share this answer
 
C#
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = ((new Char[] {'0','1','2','3','4','5','6','7','8','9'}).ToList<Char>()).Contains(e.KeyChar)?false:true;

//you can either change it to 
e.Handled = char.IsDigit(e.KeyChar) ? false : true;

}
 
Share this answer
 
v2
Comments
CHill60 14-May-14 8:19am    
Or even e.Handled = !char.IsDigit(e.KeyChar); as IsDigit returns a Boolean anyway
Use ajax it's so simple to apply validate control.
Put ajax FilterTexboxExtender and choose FilterType="Numbers" Then you will get only interger value
<ajaxtoolkit:toolkitscriptmanager id="ajsm"  runat="server" ></ajaxtoolkit:toolkitscriptmanager>
<asp:textbox id="TextBox1" runat="server" ></asp:textbox>
<ajaxtoolkit:filteredtextboxextender id="fteIn"  runat="server" targetcontrolid="TextBox1" filtertype="Numbers" >  </ajaxtoolkit:filteredtextboxextender> 
 
Share this answer
 
v2
Comments
phil.o 14-May-14 6:47am    
Seeing OP's question, it is a Windows Forms project.
Ajax is not relevant in this case.
[no name] 14-May-14 6:53am    
good
[no name] 14-May-14 10:20am    
Yes #phil.o its a Windows Forms Apps. And I also don't think Ajax is relevant over here. Anyways, I got the solution already. <br>
`private void Quantity_txt_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!Char.IsDigit(ch) && ch != 8)
{
e.Handled = true;
}
}`

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