C#文本框验证应该只接受整数值,但也允许使用字母

时间:2010-04-02 22:46:25

标签: c# validation textbox integer console-application

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

4 个答案:

答案 0 :(得分:2)

您没有指定此代码的运行位置,但我的假设是它会在按键运行时运行。由于在处理字符并更新Text属性之前收到了键入,因此检查.Text == ""将阻止其余的验证运行,至少对于第一个字符。

您应该检查与检查按下的键不同的事件的空值。

答案 1 :(得分:1)

我认为您可以使用IsDigit功能。

这些方面的东西:

string textBoxText = "12kj3";

if (!textBoxText.Equals(String.Empty))  // this forces user to enter something
{
    foreach (char c in textBoxText.ToArray())
    {
        if (!Char.IsDigit(c))
        {
            //return false;
        }
    }

    //return true;
}
else
{
    Console.WriteLine("Cannot be empty!");
}

希望你明白这一点。

答案 2 :(得分:0)

您可以使用以下RegEx检查它是否为“^ \ d + $”并且是必需的。

答案 3 :(得分:0)

bool bV=false;
    private void textBox1_Validated(object sender, EventArgs e)
    {
        TextBox textBoxText = sender as TextBox;

        if (!textBoxText.Equals(String.Empty))  
        {
            foreach (char c in textBoxText.Text.ToArray())
            {
                if (!Char.IsDigit(c))
                {
                    if (!bV)
                    {
                        MessageBox.Show("Input value not valid plase Insert Integer Value");
                        bV = true;
                        textBox1.Text = String.Empty;
                        break;
                    }
                }
            }
        }
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        bV = false;
    }