转载: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;
这样就可以了。