如何处理来自DataGridView的错误

问题描述:

当我使用带有重载的ToString()方法的类对象加载组合框的列时,我收到dataGridView的异常。如何处理来自DataGridView的错误

我已经尝试了一切,我可以在互联网上找到,以防止这个错误,我还有另一个开放的问题,所以试图排除这一个,但我没有成功。

我收到的最直接的答案是处理错误信息,并阻止它加载,在这种程度上我搜索了一遍,并创建了这种方法,我相信应该可以解决这个问题。

private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) 
{ 
    anError.Cancel = true; 
} 

它有点粗糙,但我相信它应该工作,但是当我添加断点,错误仍然存​​在,从不闯入这个功能。我之前从未做过任何错误处理,而且很可能我错过了一些东西。

所有协助赞赏。

+0

http://www.codeproject.com/Articles/18814/A-method-that-provides-how-to-handle-events-when-m将帮助你 – 2013-05-01 07:05:06

+0

你不需要做任何事情,即使处理空,它会忽略错误。在没有错误的地方我已经有了这个。 – Derek 2013-05-01 08:15:34

+0

刚刚尝试了什么德里克建议。它没有奏效。我有类Form1中的那个事件处理函数,它是否在别的地方? – 2013-05-01 11:32:33

是的,它毕竟是简单的。

private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) 

需要重新命名。

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError) 

首都D女士们,先生们。

感谢您的帮助。

德一看这...

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

您必须在文件 “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()); 
    }