Where to catch unhandled exception when editing datagridview

主宰稳场 提交于 2019-12-11 06:24:12

问题


I have a datagridview which is databound to an Entity Framework "table":

    public ObjectSet<TEntity> tableData { get; private set; }
    private BindingSource tableBinding;

    public AuxiliaryTableEditor(ObjectSet<TEntity> something)
    {
        InitializeComponent();

        this.tableData = something;
        this.tableBinding = new BindingSource();
        this.tableBinding.DataSource = tableData;

        this.auxiliaryTableEditorGridView.DataSource = tableBinding;
    }

This works perfectly fine.

The problem is this: If a user starts editing / adding a row, if they enter into edit mode in a cell, erase the contents, then tab or click out of it, an unhandled exception will be thrown (as most of the db columns do not allow nulls). This is prefectly normal and acceptable, but I would like to be able to catch and handle these exceptions, and I don't know where / how to catch them.

I have tried using several different event handlers on the datagridview, such as .DataError, .RowValidating, and a few others that I don't remember now... But I can't seem to catch the pesky exceptions.

Any suggestions are greatly appreciated!

EDIT: I should add that the exception is typically something like this: "ConstraintException was unhandled by user code. This property cannot be set to a null value".


回答1:


Try the CellEditEnding or CurrentCellChanged events.

Edit: Or you can also have the setter of your property handle the null value..

public int Number
{
  get { return _number; }
  set
  {  
      if (null == value)
      {
          // handle here
      }
  }
}

Edit: See Entity Framework error when submitting empty fields for more info.



来源:https://stackoverflow.com/questions/13826148/where-to-catch-unhandled-exception-when-editing-datagridview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!