Click here to Skip to main content
15,906,625 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
hi i want not to enter dot as first character in textbox
i tried with this code...but the problem is it is not entering dot in entire text box...
pls solve this

C#
if (char.IsDigit(e.KeyChar) || e.KeyChar == 8 || e.KeyChar != '.')
                    {
                        e.Handled = false;
                    }
                    else
                    {
                        e.Handled = true;
                    }
Posted
Comments
Sandeep Mewara 21-Jul-12 1:33am    
And the reason behind repost?
http://www.codeproject.com/Questions/425225/validate-to-enter-first-character-dot-in-csharp

C#
TextBox textbox = sender as TexBox;
while(textbox.Text.StartsWith("."))
{
   textbox.Text = textbox.Text.Remove(0, 1);
}
 
Share this answer
 
Two options:

Use a NumericUpDown instead. NumericUpDown does the filtering for you, which is nice. Of course it also gives your users the ability to hit the up and down arrows on the keyboard to increment and decrement the current value.

Handle the appropriate keyboard events to prevent anything but numeric input. I've had success with this two event handlers on a standard TextBox:

C#
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsControl(e.KeyChar) 
        && !char.IsDigit(e.KeyChar) 
        && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    // only allow one decimal point
    if (e.KeyChar == '.' 
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }
}

You can remove the check for '.' (and the subsequent check for more than one '.') if your TextBox shouldn't allow decimal places. You could also add a check for '-' if your TextBox should allow negative values.
 
Share this answer
 
Comments
Member 9068558 21-Jul-12 1:18am    
ITS ALLOWING DOT AS FIRST CHAR...MY REQUIREMENT IS NOT TO ENTER DOT AS FIRST CHAR
Use as
C#
if (e.KeyChar == '.')
           {
               if(textBox1.TextLength<1)
               e.Handled = true;
           }
           else
           {
               e.Handled = false;
           }
 
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