在DataGridView控件中验证数据输入

实现效果:

  

知识运用:

  DataGridView控件的公共事件CellValidating

   //将System.Windows.Forms.DataGridViewCellValidatingEventArgs类的Cancel属性设为true  将阻止光标离开单元格

  和CellEndEdit来处理

实现代码:

 private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == 0) //验证指定列 { float result=0; //定义值类型并赋值 if (!(float.TryParse(e.FormattedValue.ToString(), out result))) //判断是否为数值类型 { dataGridView1.Rows[e.RowIndex].ErrorText = "请输入数值类型的数据"; //提示错误信息 e.Cancel = true; //事件取消的值 } } } private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == 0) { dataGridView1.Rows[e.RowIndex].ErrorText = ""; } }

 

相关文章