textBox1_KeyDown 事件里,
如果输入的是数字以外的文字,不接受输入。
如果输入的是数字的话,接受输入,
比如:输入的是,1122a 的话,textBox1 里的内容是,1122
请问代码怎么写?

解决方案 »

  1.   

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
                {
                    if (!(Char.IsNumber(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Enter))
                    {
                        e.Handled = true; // 只允许数字键 回格 和 回车
                    }
                    else
                        e.Handled = false;
                }
      

  2.   

    KeyPress事件,调用
    //判斷是否為數字及'.'
            public static bool IsDigitalAndDot(char c)
            {
                char back = (char)8;
                if (char.IsDigit(c) || (bool)(c == back) || (c == '.'))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            } private void txtNumKeyPress(object sender, KeyPressEventArgs e)
            {
                if (!IsDigitalAndDot(e.KeyChar))
                {
                    e.Handled = true;
                }
            }
      

  3.   

    这个是最简单不过了哈哈,屡试不爽啊:
    private void txt_KeyPress(object sender, KeyPressEventArgs e)
            {
                if ("0123456789".IndexOf(e.KeyChar) == -1 && e.KeyChar != (char)Keys.Back)
                {
                    e.Handled = true;
                }
            }
      

  4.   

    <script type="text/javascript">
            var Isnum = function (num)
            {
                if (isNaN(num))
                {
                    //注意,这里空字符
                }
            }
        </script>
      

  5.   


    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        e.Handled = !Char.IsNumber(e.KeyChar);
    }