如何处理来自数据网格视图的数据错误
本文关键字:数据 数据网 网格 视图 错误 何处理 处理 | 更新日期: 2023-09-27 18:11:49
我收到一个异常从dataGridView当我加载一个ComboBox的列与类对象重载ToString()
方法。
我已经尝试了我能在互联网上找到的一切,以防止这个错误,我有另一个开放的问题,所以试图整理这个也,但我是不成功的。
我收到的最直接的答案,是处理错误信息,并阻止它加载,在这个程度上,我已经谷歌了一下,并创建了这个方法,我相信应该解决这个问题。
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
anError.Cancel = true;
}
这有点粗糙,但我相信它应该工作,但是当我添加一个断点,错误仍然存在,并且永远不会进入这个函数。我以前从来没有做过错误处理,很可能我错过了一些东西。
想法吗?
看看这个…
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
MessageBox.Show("Error happened " + anError.Context.ToString());
if (anError.Context == DataGridViewDataErrorContexts.Commit)
{
MessageBox.Show("Commit error");
}
if (anError.Context == DataGridViewDataErrorContexts.CurrentCellChange)
{
MessageBox.Show("Cell change");
}
if (anError.Context == DataGridViewDataErrorContexts.Parsing)
{
MessageBox.Show("parsing error");
}
if (anError.Context == DataGridViewDataErrorContexts.LeaveControl)
{
MessageBox.Show("leave control error");
}
if ((anError.Exception) is ConstraintException)
{
DataGridView view = (DataGridView)sender;
view.Rows[anError.RowIndex].ErrorText = "an error"; view.Rows[anError.RowIndex].Cells[anError.ColumnIndex].ErrorText = "an error";
anError.ThrowException = false;
}
}
阅读此链接:DataGridViewDataErrorEventArgs
是的,毕竟很简单。
private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
需要重命名
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
大写D,女士们,先生们。
感谢所有的帮助。
你必须在项目的"YourForm.Designer.cs"文件中插入一行代码
this.dataGridView1.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(this.dataGridView1_DataError);
将此方法添加到文件"YourForm.cs"
private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)
{
MessageBox.Show("Error happened " + anError.Context.ToString());
}