仅数字文本框

Gri*_* W. 1 c# numerical-analysis windows-phone-7

我到处都看了,但似乎我见过的例子只允许数字0-9

我正在撰写毕达哥拉斯定理计划.我希望手机(Windows Phone 7)检查文本框中是否有任何 alpha(AZ,az),符号(@,%)或其他任何数字.如果没有,那么它将继续计算.我想检查,以便将来没有错误.

这基本上是我想要它做的坏伪代码

txtOne - >任何alpha? - 否 - >任何符号 - 否 - >继续......

我实际上更喜欢一个命令来检查字符串是否完全是一个数字.

提前致谢!

Mar*_*lon 9

确保文本框是数字的更好方法是处理KeyPress事件.然后,您可以选择要允许的字符.在以下示例中,我们禁止所有不是数字的字符:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    // If the character is not a digit, don't let it show up in the textbox.
    if (!char.IsDigit(e.KeyChar))
        e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

这可以确保您的文本框文本是一个数字,因为它只允许输入数字.


这是我想出的允许十进制值(显然是退格键)的东西:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (char.IsDigit(e.KeyChar))
    {
        return;
    }
    if (e.KeyChar == (char)Keys.Back)
    {
        return;
    }
    if (e.KeyChar == '.' && !textBox1.Text.Contains('.'))
    {
        return;
    }
    e.Handled = true;
} 
Run Code Online (Sandbox Code Playgroud)

  • 通常你也必须处理从剪贴板粘贴,但我不知道这是否是Windows Phone 7上的问题. (2认同)