The DataGridView control is a Windows Forms control derived from theControl base class, and it is a complex data container. The DataGridView control lets you handle validation at several levels. The grid itself is a control, and thus raise^alidating and Validated events when the focus shifts away from the grid. However, usually you will want to handle validating a little closer to the data that is being validated, either at the individual row or cell level. To allow this, the DataGridView fires RowValidating and RowValidated events each time the selected row changes within the grid. Likewise, as the focus shifts from cell to cell within the grid, CellValidating and CellValidated events fire as well.
These events follow the same pattern as the control validating events, letting you cancel validation by setting their event argument Cancel property to true. In the case of the RowValidating event, the event argument type isDataGridViewCellCancelEventArgs; for CellValidating, the event argument type isDataGridViewCellValidatingEventArgs. Both of these types give you access to the current Rowlndexand Columnlndex, and they have aCancel property that can be set toTRue to cancel validation. The DataGridView control is designed to keep the focus on the current cell if validation fails.
As you may remember from earlier in the book, each time you shift focus in a data-bound grid, a CellParsing event fires for the cell you are leaving, and a CellFormatting event fires for the cell you have moved to. These events let you modify the displayed data as it goes out to and comes in from the data source, respectively. With respect to validation, you should be aware that the CellValidating event fires before the CellParsing event. So the validation logic you apply in a handler for theCellValidating event should validate against the display patterns for the cell, which don't necessarily map directly to the storage patterns for the corresponding data member in the data source. If you are doing conversions or formatting for display purposes, and want to validate the data before it gets pushed back into the underlying data source but after the parsing process has occurred, you will want to call that logic in the CellParsing event handler, not the CellValidating event handler.
Was this article helpful?