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

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

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

     实现: 选择DataGridView的CellValidating事件

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

      (1)  验证整数:

WinForm中DataGridView验证单元格输入的是数字 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) 验证十进制数:

 

WinForm中DataGridView验证单元格输入的是数字 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         }

 

           

           

          

         

你可能感兴趣的:(datagridview)