Monday, March 11, 2013

How to Validate/Restrict TextBox for Entering Only Number or Characters(if Required)

(Can’t enter any special characters and can’t paste characters using ctrl+V)


1. Number Only Textbox with backspace

1.      For that we can use keyPress event of the textbox

2.       Double click the keyPress event of the textbox

3.       Here is the code, Copy and paste the same code. Now it will work
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsNumber(e.KeyChar) == false)
{
      //This code is for pressing BackSpace
if ((e.KeyChar == (char)Keys.Back)) return;
e.Handled = true;
}
}

//Or we can use this code for the same validation

private void textBox3_KeyPress(object sender, KeyPressEventArgs e)

{

      if ((e.KeyChar != (char)Keys.Back) && !char.IsDigit(e.KeyChar))

      {
            e.Handled = true;
      }           
} 

2. Number Only Textbox with backspace and only one dot
Now we can check how to  type float/decimal characters i.e number with only one ‘.’ (dot/point)

private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
    //Here is the code that will allow only one decimal point
    if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
    {
          e.Handled = true;
    }
    if (char.IsNumber(e.KeyChar) == false)
    {
        if ((e.KeyChar == (char)Keys.Back) || e.KeyChar == '.') return;
          e.Handled = true;
    }
}

//Or we can use this code for the same validation
private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
{
    if ((e.KeyChar != (char)Keys.Back) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
     {
        e.Handled = true;
     }
     //Here is the code that will allow one decimal point
     if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1)
     {
        e.Handled = true;
     }
}


3. If we want to add only one character and other number only means we can replace ‘.’(dot/point) with the special characters like A~Z or a~z or  ,;[]' " \ etc

private void textBox3_KeyPress(object sender, KeyPressEventArgs e)

{
    //Here is the code that will allow only one character ‘c’
    if (e.KeyChar == 'c' && (sender as TextBox).Text.IndexOf('c') > -1)
    {
          e.Handled = true;
    }
    if (char.IsNumber(e.KeyChar) == false)
    {
        if ((e.KeyChar == (char)Keys.Back) || e.KeyChar == 'c') return;
          e.Handled = true;
    }
}

No comments:

Post a Comment

Comment Here..