捕捉用户向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方法时,编辑方式就不能终了。 本文转自:http://bingning.net/VB/SOURCE/datagridview/dataerror.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |