单击DataGridView列中的按钮时禁止验证

时间:2014-07-21 12:43:11

标签: vb.net winforms datagridview

当用户点击WinForms DataGridView中的按钮时,是否可以取消验证?我使用DataGridViewButtonColumn作为按钮列。 VB.Net和.Net 4.0。


我有一个用户输入文件路径的列,旁边有一个按钮列。用户可以单击这些按钮以显示常用对话框并浏览文件,所选文件路径将存储在第一列中。在CellValidating事件中,我验证文件路径是否存在。但是,当用户单击“浏览”按钮选择其他文件时,应用此验证不是用户友好的!

对于独立按钮,我会将CausesValidation设置为False。但我不想禁用整个DataGridView的验证,只需按钮。我在DataGridViewButtonColumn上找不到任何合适的属性。

Private Sub mDataGridView_CellValidating(ByVal sender As Object, 
  ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) 
  Handles mDataGridView.CellValidating

  Dim sValue As String = e.FormattedValue.ToString

  If e.ColumnIndex = 0 Then
    If Not IO.File.Exists(sValue) Then
      MsgBox("The file does not exist.")
      e.Cancel = True
    End If
  End If
End Sub

1 个答案:

答案 0 :(得分:0)

社区根本没有回应,所以我努力工作并在this MSDN forum post找到答案!

Private Sub mDataGridView_CellValidating(ByVal sender As Object, 
  ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) 
  Handles mDataGridView.CellValidating 

  Dim sValue As String = e.FormattedValue.ToString

  If e.ColumnIndex = 0 Then
    'Find current mouse cursor position
    Dim p As Point = mDataGridView.PointToClient(Cursor.Position)
    Dim hit As DataGridView.HitTestInfo = mDataGridView.HitTest(p.X, p.Y)
    If (hit.Type = DataGridViewHitTestType.Cell) Then
      'Mouse is over a cell
      If hit.ColumnIndex = <column containing browse button> Then
        If hit.RowIndex = e.RowIndex Then
          'And it's a browse button cell for the same row. Abort validation here.            
          Exit Sub
        End If
      End If
    End If

    If Not IO.File.Exists(sValue) Then
      MsgBox("The file does not exist.")
      e.Cancel = True
    End If
  End If
End Sub