zoukankan      html  css  js  c++  java
  • winfrom 限制文本框小数点后两位

     private void numWeight_KeyPress(object sender, KeyPressEventArgs e)
            {
    
                if (char.IsNumber(e.KeyChar) || e.KeyChar == '.' || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Delete)
                {
                    e.Handled = false;          //让操作生效     
                    int j = 0;                  //记录小数点个数  
                    int k = 0;                  //记录小数位数  
                    int dotloc = -1;            //记录小数点位置  
                    bool flag = false;          //如果有小数点就让flag值为true  
                    for (int i = 0; i < numWeight.Text.Length; i++)
                    {
                        if (numWeight.Text[i] == '.')
                        {
                            j++;
                            flag = true;
                            dotloc = i;
                        }
                        if (flag)
                        {
                            if (char.IsNumber(numWeight.Text[i]) && e.KeyChar != (char)Keys.Back && e.KeyChar != (char)Keys.Delete)
                            {
                                k++;
                            }
                        }
                        if (j >= 1)
                        {
                            if (e.KeyChar == '.')
                            {
                                if (numWeight.SelectedText.IndexOf('.') == -1)
                                    e.Handled = true;//输入“.”,选取部分没有“.”操作失效  
                            }
                        }
                        if (!flag)                  //此处控制没有小数点时添加小数点是否满足两位小数的情况  
                        {
                            if (e.KeyChar == '.')
                            {
                                if (numWeight.Text.Length - numWeight.SelectionStart - numWeight.SelectedText.Length > 2)        //the condition also can be instead of "textBox1.Text.Substring(textBox1.SelectionStart).Length-textBox1.SelectionLength>2"   
                                    e.Handled = true;
                            }
                        }
                        if (k == 2)
                        {
                            if (numWeight.SelectionStart > numWeight.Text.IndexOf('.') && numWeight.SelectedText.Length == 0 && e.KeyChar != (char)Keys.Delete && e.KeyChar != (char)Keys.Back)      //如果已经有两位小数,光标在小数点右边,  
                                e.Handled = true;
                        }
                    }
                }
                else
                {
                    e.Handled = true;
                }
            }
    View Code
  • 相关阅读:
    编程是点滴的积累
    Tech.ED 2005 北京 第二天印象
    Tech.ED 2005 北京 第三天印象
    别把事情弄的太复杂
    在看《青衣》
    可以用的开源包
    KVM虚拟机的性能问题
    [zz]kvmlibvirt的使用:创建虚拟机与快照
    KVM快照snapshot
    [zz]kvm环境快照(snapshot)的使用方法
  • 原文地址:https://www.cnblogs.com/mm08290523/p/5363705.html
Copyright © 2011-2022 走看看