简单谈谈如何在DataGridView控件中验证数据输入的正确性,winform

简单谈谈如何在DataGridView控件中验证数据输入的正确性,winform

实现DataGridView控件中验证数据输入功能主要是利用DataGridView控件的公共事件CellValidatingCellEndEdit事件在为当前选定的单元格停止编辑模式时发生。

本实例判断控件第一列中单元格的值是否为空。在CellValidating事件中进行验证,如果严重失败,将System.Windows.Forms.DataGridViewCellValidatingEventArgs类的Cancel属性设置为True。这将导致DataGridView控件阻止光标离开该单元格。将该行的ErrorText属性设置为解释性字符串,将显示错误图标,其工具提示将保护此错误文本。在CellEndEdit事件处理程序中,将该行的ErrorText属性设置为空字符串。只有当单元格退出编辑模式(如果验证失败,则不能退出单元格)时,才能发生CellEndEdit事件。运动程序,编辑控件的第一列,在单元格中不输入内容,然后使用鼠标单击其他单元格,这样就会提示错误

在此给出大家主要代码:

 

Private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e)

 {

   If (e.ColumnIndex==0)

     {

         If(String.IsNullOrEmpty(e.FormattedValue.ToString))

         {

           dataGridView1.Rows[e.RowIndex].ErrorText=”单元格第一列值不能为空

           e.Cancel=true;

         }

     }

}

Private void dataGridView1_CellEndEdit(object sender,DataGridViewCellEventArgs e)

{

      dataGridView1.Rows[e.RowIndex].ErrorText=String.Empty;

}

原文地址:https://www.cnblogs.com/hfzsjz/p/1899201.html