Click here to Skip to main content
15,902,189 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
i used below coding. but its accepting alphabets also., how to prevent this.,
[i given keypreview=false and tried with keypreview=true]

C#
private void txtorate_KeyPress(object sender,KeyPressEventArgs e)
        {

            if(!char.IsControl(e.KeyChar)&&(!char.IsDigit(e.KeyChar))&& e.KeyChar!='.')
            {
                e.Handled = true;
            }

            if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
            {
                e.Handled = true;
            }
        }
Posted
Comments
Matt T Heffron 2-Oct-12 13:30pm    
I don't see a problem with this at all.
It allows digits, the decimal point, and control characters like Ctrl-C (Copy), Ctrl-V (Paste), etc. All other characters are ignored.
What is the problem you are seeing?

By the way, instead of the hard-coded '.', you might want to use CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator. This is a string, not char, so checking could be more difficult. :(
Sergey Alexandrovich Kryukov 2-Oct-12 21:23pm    
Good point, about the culture...
And yes, this is not a question at all. Again...
--SA

Why not use a NumericUpDown[^] instead? That is pretty much what it was designed for...
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Oct-12 21:25pm    
Well, about the vote of 3... I'm really surprised that some moron did not vote 1. This is what usually happens when we answer like this.
But in fact, this is the best solution, by far. My 5.
--SA
See this MSDN article which shows you the code:
http://msdn.microsoft.com/en-us/library/ms229644%28v=vs.80%29.aspx[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 2-Oct-12 21:27pm    
I voted 4, not 5 only because you did not suggest the obvious and best solution, which would be the same as Solution 1 -- please see and appreciate it.
--SA
Use || instead of && in first condition:

C#
private void txtorate_KeyPress(object sender,KeyPressEventArgs e)
{
    if(!char.Control(e.KeyChar) || (!char.IsDigit(e.KeyChar)) || e.KeyChar != '.')

        if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)

                e.Handled = true;
}

I think it would help.
 
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