如何处理DataGridView中的错误

时间:2013-05-01 06:28:56

标签: c# .net error-handling

当我使用带有重载ToString()方法的类对象加载ComboBox的列时,我收到了dataGridView的异常。

我已经尝试了我可以在互联网上找到的所有内容,以防止出现此错误,我还有另一个未解决的问题,试图对此进行排序,但是我没有成功。

我收到的最简单的答案是处理错误消息,并阻止它加载,在这种程度上我已经用Google搜索,并创建了我认为应该解决问题的方法。

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

它有点粗糙,但我相信它应该可行,但是当我添加一个断点时,错误仍然存​​在,并且永远不会破坏这个功能。我之前从未做过任何错误处理,我很可能错过了一些东西。

所有的帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

看看这个......

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

答案 1 :(得分:0)

是的,毕竟很简单。

private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)

需要重命名。

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)

Capital D女士们,先生们。

感谢所有的帮助。

答案 2 :(得分:0)

您必须在项目中的文件" 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());
    }