假设网格视图中包含两个列: “StartTime” 和 “EndTime”。 在同一行中,第一个列中的值必须小于第二个列中的值。 因此在把数据保存到数据源之前,需要对行执行验证。 为了达到此目的,接管了 ColumnView.ValidateRow 事件。

如果行验证失败,则通过 ColumnView.SetColumnError 方法使用相应的错误说明,为列设置错误。 当鼠标指针停留在错误图标上时,错误说明将被显示。

为了阻止显示默认的错误消息框,接管了 ColumnView.InvalidRowException 事件。

下面的屏幕截图展示了在行验证未通过之后的一个网格视图。

C#CopyCode image复制代码
using DevExpress.XtraGrid.Views.Base;
using DevExpress.XtraGrid.Columns;

private void gridView1_ValidateRow(object sender, 
DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e) {
    ColumnView view = sender as ColumnView;
    GridColumn column1 = view.Columns["StartTime"];
    GridColumn column2 = view.Columns["EndTime"];
    //Get the value of the first column
    DateTime time1 = (DateTime)view.GetRowCellValue(e.RowHandle, column1);
    //Get the value of the second column
    DateTime time2 = (DateTime)view.GetRowCellValue(e.RowHandle, column2);            
    //Validity criterion
    if (time1 >= time2) {
        e.Valid = false;
        //Set errors with specific descriptions for the columns
        view.SetColumnError(column1, "The value must be less than EndTime");
        view.SetColumnError(column2, "The value must be greater than StartTime");
    }
}

private void gridView1_InvalidRowException(object sender, 
DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e) {
    //Suppress displaying the error message box
    e.ExceptionMode = ExceptionMode.NoAction;
}

Visual BasicCopyCode image复制代码
Imports DevExpress.XtraGrid.Views.Base
Imports DevExpress.XtraGrid.Columns

Private Sub GridView1_ValidateRow(ByVal sender As Object, _
ByVal e As DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs) _
Handles GridView1.ValidateRow
    Dim view As ColumnView = CType(sender, ColumnView)
    Dim column1 As GridColumn = View.Columns("StartTime")
    Dim column2 As GridColumn = View.Columns("EndTime")
    'Get the value of the first column
    Dim time1 As DateTime = CType(view.GetRowCellValue(e.RowHandle, column1), DateTime)
    'Get the value of the second column
    Dim time2 As DateTime = CType(view.GetRowCellValue(e.RowHandle, column2), DateTime)
    'Validity criterion
    If time1 >= time2 Then
        e.Valid = False
        'Set errors with specific descriptions for the columns
        View.SetColumnError(column1, "The value must be less than EndTime")
        View.SetColumnError(column2, "The value must be greater than StartTime")
    End If
End Sub

Private Sub GridView1_InvalidRowException(ByVal sender As Object, _
ByVal e As DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs) _
Handles GridView1.InvalidRowException
    'Suppress displaying the error message box
    e.ExceptionMode = ExceptionMode.NoAction
End Sub