【问题标题】:How to handle a Data error from Data Grid View如何处理来自数据网格视图的数据错误
【发布时间】:2013-04-25 04:34:06
【问题描述】:

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

我已经尝试了所有可以在互联网上找到的方法来防止这个错误,我还有另一个关于 SO 的悬而未决的问题也试图解决这个问题,但是我没有成功。

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

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

它有点粗糙,但我相信它应该可以工作,但是当我添加一个断点时,错误仍然存​​在,并且永远不会中断这个函数。我以前从未做过任何错误处理,很可能我遗漏了什么。

想法?

【问题讨论】:

  • 您不需要做任何事情,即使句柄为空,它也会忽略错误。我以前有过这个,没有错误。
  • 刚刚尝试了 Derek 的建议。它没有奏效。我在 Form1 类中有那个事件处理函数,它是否意味着在其他地方?

标签: c# .net error-handling


【解决方案1】:

是的,毕竟很简单。

private void DataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)

需要重命名。

private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs anError)

Capital D 女士们先生们。

感谢您的所有帮助。

【讨论】:

    【解决方案2】:

    看看这个...

    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

    【讨论】:

    • 我建议做这样的事情 if (anError.Context.HasFlag(DataGridViewDataErrorContexts.Parsing)) {...} 因为 DataGridViewDataErrorContexts 枚举是一个标志类型的枚举,并不总是只包含某些值
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-05
      • 2014-01-15
      • 2012-09-20
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 1970-01-01
      • 2014-08-10
      相关资源
      最近更新 更多