C# Textbox validation should only accept integer values, but allows letters as well

Posted by sonny5 on Stack Overflow See other posts from Stack Overflow or by sonny5
Published on 2010-04-02T22:46:25Z Indexed on 2010/04/02 22:53 UTC
Read the original article Hit count: 468

Filed under:
if (textBox1.Text != "")  // this forces user to enter something
{
  // next line is supposed to allow only 0-9 to be entered but should block all...
  // ...characters and should block a backspace and a decimal point from being entered....
  // ...but it is also allowing characters to be typed in textBox1
  if(!IsNumberInRange(KeyCode,48,57) && KeyCode!=8 && KeyCode!=46)  // 46 is a "."
  {  
     e.Handled=true;
  }
  else 
  {
     e.Handled=false;
  }  

  if (KeyCode == 13) // enter key
  {  
    TBI1 = System.Convert.ToInt32(var1);   // converts to an int
    Console.WriteLine("TBI1 (var1 INT)= {0}", var1);
    Console.WriteLine("TBI1= {0}", TBI1);
  } 

  if (KeyCode == 46)
  {
    MessageBox.Show("Only digits...no dots please!"); 
    e.Handled = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar); 
  }
}
else
{
   Console.WriteLine("Cannot be empty!");
}

// If I remove the outer if statement and skip checking for an empty string, then
// it prevents letters from being entered in the textbox. I need to do both, prevent an 
// empty textbox AND prevent letters from being entered.
// thanks, Sonny5

© Stack Overflow or respective owner

Related posts about c#