C# winform textbox只能输入数字

        //控制只能输入整数或小数
        //小数位最多位4位,小数位可以自己修改
        private void KeyPressCheckNum(object sender, KeyPressEventArgs e)
        {
            //e.Handled = true;
            //if (e.KeyChar >= '0' && e.KeyChar <= '9')
            //{
            //    e.Handled = false;
            //}
            if (!(((e.KeyChar >= '0') && (e.KeyChar <= '9')) || e.KeyChar <= 31))
            {
                if (e.KeyChar == '.')
                {
                    if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                        e.Handled = true;
                }
                else
                    e.Handled = true;
            }
            else
            {
                if (e.KeyChar <= 31)
                {
                    e.Handled = false;
                }
                else if (((TextBox)sender).Text.Trim().IndexOf('.') > -1)
                {
                    if (((TextBox)sender).Text.Trim().Substring(((TextBox)sender).Text.Trim().IndexOf('.') + 1).Length >= 4)
                        e.Handled = true;
                }
            }

        }

 

 

posted @ 2011-03-29 21:31  trace007  阅读(696)  评论(1编辑  收藏  举报