Click here to Skip to main content
15,894,896 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am developing a windows application where i need to validate the textbox which can accept only numeric value, single dot(.), and backspace and delete key. for this i am writing this code
C#
if ((e.KeyChar=='.' && textBox1.Text.IndexOf('.')>-1) || char.IsLetter(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsSymbol(e.KeyChar))
           {
               e.Handled = true;
           }

but it is not accepting the dot(.) because (.) comes under punctuation. please help me
to do this which accepts the (.) except others punctuation.
Posted
Updated 7-Sep-12 8:15am
v2

Why use a textbox?
Use a NumericUpDown instead - it looks like a textbox (with an up and a down arrow), it works like a text box, but it has the validation already built in.
 
Share this answer
 
Comments
Imteyaz Ahmed 7-Sep-12 14:25pm    
i cannot use numeric updown key. i need validation on textbox.
It would be a little simpler:

if ((e.KeyChar=='.' && textBox1.Text.IndexOf('.')>-1) || ! e.KeyChar==Keys.Delete && ! e.KeyChar==Keys.Back || !  char.IsDigit(e.KeyChar))
{
  e.Handled = true;
}
 
Share this answer
 
v2
hiii,
try this

C#
if (  char.IsLetter(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsSymbol(e.KeyChar))
           {
               if ((e.KeyChar == '.' && textBox1.Text.IndexOf('.')>-1 ))
               {
                   e.Handled = true;
               }
           }
 
Share this answer
 
if ((e.KeyChar == '.' && textBox1.Text.IndexOf('.') > -1) || char.IsLetter(e.KeyChar) || (e.KeyChar >= (char)33 && e.KeyChar <= (char)45) || char.IsSymbol(e.KeyChar) || (e.KeyChar >= (char)58 && e.KeyChar <= (char)64) || (e.KeyChar >= (char)91 && e.KeyChar <= (char)96) || (e.KeyChar >= (char)123 && e.KeyChar <= (char)126) || e.KeyChar=='/')
{
e.Handled = true;
}
 
Share this answer
 
But your code is correct.

C#
if ((e.KeyChar=='.' && textBox1.Text.IndexOf('.')>-1) || char.IsLetter(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsSymbol(e.KeyChar))
            {
                e.Handled = true;
            }




You are checking the char is . in the first condition and returing true.Why it is going for the next Or condition.
 
Share this answer
 

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