c#中设置像数量,价格,金额等的textbox的限制条件,用户只能输入数字或小数(小数及负号只能输一次)

来源:互联网 发布:什么软件可以发表文章 编辑:程序博客网 时间:2024/04/29 13:41

       //判断按键是不是要输入的类型。
         if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar !=46 && (int)e.KeyChar !=45 )
            e.Handled = true;

         //小数点的处理。
         if ((int)e.KeyChar == 46){                           //小数点
            if (txtAdjustment.Text.Length <= 0)
                e.Handled = true;   //小数点不能在第一位

            else{                                             //处理不规则的小数点
                char strAdjustment = Convert.ToChar(txtAdjustment.Text.Substring(0,1));
                if((int)strAdjustment == 45 && txtAdjustment.Text.Length == 1)  //小数点不能在负号后面
                    e.Handled = true;  
                else{
                    float f;
                    float oldf;
                    bool b1 = false, b2 = false;
                    b1 = float.TryParse(txtAdjustment.Text, out oldf);
                    b2 = float.TryParse(txtAdjustment.Text + e.KeyChar.ToString(), out f);
                    if (b2 == false){
                        if (b1 == true)
                            e.Handled = true;
                        else
                            e.Handled = false;
                    }
                }
            }
        }else if((int)e.KeyChar == 45){                          //负号
           if (txtAdjustment.Text.Length >= 1)
                e.Handled = true;   //负号只能在第一位
        }


参考文档:http://blog.sina.com.cn/s/blog_a9091a33010162iv.html

0 0
原创粉丝点击