我正在使用通过BindingSource控件连接到数据库表的DataGridView控件。该表包括日期/时间字段。当在对应于日期/时间字段和提交的行的单元格中输入格式不正确的日期时,我看到一个屏幕标题为DataGridView的默认错误处理程序,带有异常报告和调用堆栈。底部的消息说"要替换此默认对话框,请处理DataError事件"。如果我为此事件添加代码来执行此操作,程序会在尝试无效数据输入和提交时挂起,焦点无法移出具有无效数据的日期/时间单元格。我希望能够在这种情况下自定义错误消息。
答案 0 :(得分:0)
查找事件中显示的一些代码的提示显示了解决方案。我需要将e.Cancel设置为false。没有这个的代码不会进入事件,这就是我没有列出的原因
// Don't throw an exception when we're done.
e.ThrowException = false;
// Display an error message.
string txt = "Error with " +
dgvPeople.Columns[e.ColumnIndex].HeaderText +
"\n\n" + e.Exception.Message;
MessageBox.Show(txt, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// If this is true, then the user is trapped in this cell.
e.Cancel = false;