If you are binding a custom Class to your DataGridView you could Implement the
System.ComponentModel.IDataErrorInfo[
^] in your Class.
Implementation looks like this:
Public Class Person
Implements System.ComponentModel.IDataErrorInfo
Public Property FirstName As String
Public Property LastName As String
Public Property Age As Integer
Public ReadOnly Property [Error] As String Implements System.ComponentModel.IDataErrorInfo.Error
Get
Dim errorMessage As String = String.Empty
errorMessage &= Me.Item("FirstName") & "{0}"
errorMessage &= Me.Item("LastName") & "{0}"
errorMessage &= Me.Item("Age")
Return String.Format(errorMessage, Environment.NewLine)
End Get
End Property
Default Public ReadOnly Property Item(ByVal columnName As String) As String Implements System.ComponentModel.IDataErrorInfo.Item
Get
Dim errorMessage As String = String.Empty
Select Case columnName
Case "FirstName"
If Me.FirstName = String.Empty Then
errorMessage = "Firstname is a mandatory field."
End If
Case "LastName"
If Me.LastName = String.Empty Then
errorMessage = "Lastname is a mandatory field."
End If
Case "Age"
If Me.Age < 18 Or Me.Age > 80 Then
errorMessage = "Age should be a value between 18 and 80."
End If
End Select
Return errorMessage
End Get
End Property
End Class
Both the ErrorProvider and the DataGridView automatically show error icons on bound Controls and Cells/Rows when they are bound to an Object that Implements IDataErrorInfo. Then if you want to validate your Object before doing something you could simply say:
Dim p as New Person
If p.Error = String.Empty Then
Else
MessageBox.Show(String.Format("The Person is not valid.{0}{1}", Environment.NewLine, p.Error)
End If
The pro to this approach is that your validation logic is in your business Class (in this example Person). So if you would ever need to re-use the Person Class (in another Form, Assembly or Application) you do not need to rewrite (or worse, copy/paste) your validation logic. The Person validates itself.
Hope this helps! :)