Validating cell in a Datagridview - SQL Programmers

Validating cell in a Datagridview

12/04/2011

Validating cell in a DataGridView using CellValueChanged

If you want to validate the values of column in DatagridView, when the user updates a cell of that column, the CellValueChanged event is fired. The event will be called when the focus leaves cell.

CellValueChanged event is used of when you want to validate a cell in DataGridView. This can be used only in windows application not in web application.

Example

Consider a 4th column in a datagridView, it should accept the date only if the date falls on Monday. If the value is other than Monday it should not accept and throw an error message. The following code will validate the cells of particular column.

Private Sub SampleGrid_CellValueChanged(ByVal sender As System.Object, ByVal e As     System.Windows.Forms.DataGridViewCellEventArgs) Handles SampleGrid.CellValueChanged

        If e.ColumnIndex = 4 Then
            If SampleGrid.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString <> "" Then
                Dim dtDate As Date
                Dim strDay As String
                dtDate = SampleGrid.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
                strDay = dtDate.ToString("dddd")
                If strDay <> "Monday" Then
                    MsgBox("Please enter a Monday date.")
                    SampleGrid.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = ""
                    Exit Sub
                End If
            End If
        End If
End Sub

The DataGridView.CellValueChanged event occurs when the cell value has been updated.