捕捉用户向DataGridView的单元格输入不正确值时发生的错误

比如说,向定义为数字型列的单元格输入英文字母时,「DataGridView 的既定错误对话框」对话框就会表示出来,当例外发生时通知用户的一种方式。当用户没有输入正确的值时就会有对话框显示,对于用户来说可能根本就不明白为什么会出现,所以最好不要出现这样的对话框。

禁止这种对话框出现,设定DataError事件。具体的说明请参照「DataGridView的错误对话」。

下面的代码是通过设定DataError事件,表示出单独的对话框。

[VB.NET]

'DataError事件处理器
Private Sub DataGridView1_DataError(ByVal sender As Object,_
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError
If Not (e.Exception Is nothing) Then
MessageBox.Show(Me,_
String.Format("({0},{1}) 的单元格有错误。" + _
vbCrLf + vbCrLf + "说明: {2}",_
e.ColumnIndex,e.RowIndex,e.Exception.Message),_
"发生错误",_
MessageBoxButtons.OK,_
MessageBoxIcon.Error)
End If
End Sub
[C#]

//DataError事件处理器
private void DataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
if (e.Exception != null)
{
MessageBox.Show(this,
string.Format("({0},{1}) 的单元格有错误。/n/n说明: {2}",
e.ColumnIndex,
"错误发生",
MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
补充:使用DataError事件处理器可以取得DataGridViewDataErrorEventArgs对象的Context属性,这样就可以知道在什么状态下发生错误。详细的说明请参照「DataGridViewDataErrorContexts 枚举」。

还有,通过设置ThrowException属性为True,DataError事件处理器执行完后,就会出现Throw例外事件。

用户向单元输入不正确的值时,自动还原为原来的值

DataError事件处理器取得的DataGridViewDataErrorEventArgs对象的Cancel属性为False时,用户向单元格输入的值不正确时也不会出现错误,但会还原为原来的值。

[VB.NET]

'DataError事件处理器
Private Sub DataGridView1_DataError(ByVal sender As Object,_
ByVal e As DataGridViewDataErrorEventArgs) _
Handles DataGridView1.DataError
e.Cancel = False
End Sub
[C#]

//DataError事件处理器
private void DataGridView1_DataError(object sender,
DataGridViewDataErrorEventArgs e)
{
e.Cancel = false;
}
使用DataError事件处理器执行DataGridView.CancelEdit方法可以使值还原为原来的值。设置DataGridViewDataErrorEventArgs对象的Cancel属性为False时,编辑方式终了,但触发CancelEdit方法时,编辑方式就不能终了。

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/GuanXX/archive/2009/03/25/4024233.aspx

相关文章

Format[$] ( expr [ , fmt ] ) format 返回变体型 format$ 强...
VB6或者ASP 格式化时间为 MM/dd/yyyy 格式,竟然没有好的办...
在项目中添加如下代码:新建窗口来显示异常信息。 Namespace...
转了这一篇文章,原来一直想用C#做k3的插件开发,vb没有C#用...
Sub 分列() ‘以空格为分隔符,连续空格只算1个。对所选...
  窗体代码 1 Private Sub Text1_OLEDragDrop(Data As Dat...