WinForm中DataGridView验证单元格输入的是数字

简介: 转载:http://www.cnblogs.com/ganqiyin/archive/2013/02/18/2915491.html 事件:DataGridView验证单元格输入的是数字,DataGridView源数据是从数据库读取的。

转载:http://www.cnblogs.com/ganqiyin/archive/2013/02/18/2915491.html

事件:DataGridView验证单元格输入的是数字,DataGridView源数据是从数据库读取的。

     需求:当用户输入的不是数字的时候需要提示信息(数据是直接绑定数据库的,因此dataGridView有自己的报错功能,我们需要屏蔽掉它,显示自己的错误提示!)

     实现: 选择DataGridView的CellValidating事件

             

      (1)  验证整数:

View Code
 1  private void gridPlant_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
 2  {  3 if (e.RowIndex > -1 && e.ColumnIndex > -1)  4  {  5 DataGridView grid = (DataGridView)sender;  6 grid.Rows[e.RowIndex].ErrorText = "";  7 //这里最好用列名,而不是列索引号做判断  8 if (grid.Columns[e.ColumnIndex].Name == "WO0011_NUMBER_IDLE" || grid.Columns[e.ColumnIndex].Name == "WO0011_NUMBER_WORKING" || grid.Columns[e.ColumnIndex].Name == "WO0011_NUMBER_ON_SITE")  9  { 10 11 Int32 newInteger = 0; 12 if (!int.TryParse(e.FormattedValue.ToString(), out newInteger)) 13  { 14 e.Cancel = true; 15 grid.Rows[e.RowIndex].ErrorText = "Please enter a int number!"; 16 MessageBox.Show("the value is not nubmer , Pleaser enter a int number !"); 17 return; 18  } 19  } 20  } 21 }

     (2) 验证十进制数:

 

View Code
 1  private void gridBriefsOlder_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
 2  {  3 if (e.RowIndex > -1 && e.ColumnIndex > -1)  4  {  5 DataGridView grid = (DataGridView)sender;  6 grid.Rows[e.RowIndex].ErrorText = "";  7  8 if (grid.Columns[e.ColumnIndex].Name == "WO0009_APPROXIMATE_COMPLETION_PERCENTAGE1")  9  { 10 try 11  { 12  Convert.ToDecimal(e.FormattedValue); 13  } 14 catch 15  { 16 e.Cancel = true; 17 grid.Rows[e.RowIndex].ErrorText = "Please enter a number!"; 18 MessageBox.Show("the value is not nubmer , Pleaser enter a number !"); 19 return; 20  } 21  } 22  } 23 }

 

//=>不设置CausesValidation话,则datagridview中CellValidating中出现无限循环了。
this.dgvRecyclePackage.CausesValidation = false;
这样就可以了。

目录
相关文章
Winform中Textbox、NumericUpDown等修改高度,禁止输入数字或内容的实现
Winform中的Textbox、NumericUpDown控件通常在单行的情况下,无法直接通过`Height`属性修改高度,但很多时候我们需要调整其高度,使其显示的更加合理,主要介绍三种方法...
1726 0
|
10月前
|
C#
WPF限制文本框只能输入数字
WPF限制文本框只能输入数字
185 0
|
存储 前端开发 C++
2.8 输入控件(三)
2.8 输入控件(三)
2.8 输入控件(三)
|
数据安全/隐私保护 C++
2.8 输入控件(一)
2.8 输入控件(一)
2.8 输入控件(一)
|
C#
正则表达式——WPF输入控件TextBox 限定输入特定字符
原文:正则表达式——WPF输入控件TextBox 限定输入特定字符 概念: 正则表达式是对字符串操作的一种逻辑公式, 就是用事先定义好的一些特定字符、及这些特定字符的组合,组成一个“规则字符串”, 这个“规则字符串”用来表达对字符串的一种过滤逻辑。
2084 0