C# TextBox 只能输入数字

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox txt = sender as TextBox;
            //屏蔽非法按键,只能输入小数
            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '-' || e.KeyChar == '.' || e.KeyChar == 8)
            {
                if (txt.Text.Contains(".") && e.KeyChar == '.')
                {
                    e.Handled = true;             
                }
                else if (e.KeyChar == '-')
                {
                    if (txt.Text.Length != 0)
                    {
                        e.Handled = true;
                    }
                }             
            }          
            else
            {
                e.Handled = true;
            }
        }  

 

posted on 2015-09-22 14:47  strangeman  阅读(373)  评论(0编辑  收藏  举报

导航