以C#中,其控件的灵活动用很重要。在此,简要谈谈DataGridView控件,当在DataGridView控件中验证数据输入功能主要是利用
DataGridView控件的公共事件
CellValidating和
CellEndEdit事件在为当前选定的单元格停止编辑模式时发生。本实例判断控件第一列中单元格的值是否为空。在
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;
}