代码改变世界

NumericUpDown 控件输入限制小数位

2010-10-25 17:52  calm_水手  阅读(3128)  评论(1编辑  收藏  举报

在做项目的时候,需要提供给用户只能输入2为小数的功能。只允许用户输入数字的情况,自然用控件NumericUpDown,同时,该控件有个属性NumericUpDown.DecimalPlaces,该属性为:数字显示框中要显示的十进制位数。默认值为 0。单独靠这个属性,显示输入2为小数,可以。但是Value还是输入的数字。嗯,用Decimal.Round();Decimal.Floor(),再或者是截取字符串,觉得都不合适。我是这么做的:

代码
 1  private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)
 2         {
 3             if (((NumericUpDown)sender).Text.Trim().IndexOf('.'> -1)
 4             {
 5                 if (((NumericUpDown)sender).Text.Trim().Substring(((NumericUpDown)sender).Text.Trim().IndexOf('.'+ 1).Length >= 2)//定义小数位
 6                 {
 7                     if (!char.IsDigit(e.KeyChar) )
 8                     {
 9                         e.Handled = false;
10                     }
11                     else
12                     {
13                         e.Handled = true;
14                     }
15                 }
16             }
17         }

 

 

思路就是:限制输入。完事儿。