Emad-ud-deen
Emad-ud-deen

Reputation: 4864

Reset DataGridView blank row if user clicks in that row and takes focus off that row

If a user clicks the blank row at the bottom of a DataGridView and moves focus away from the DataGridView, the row click in now is in a state that indicates a change is made to that row.

Is it possible to tell the DataGridView to un-mark this row as being changed?

Is it possible to reset this row when focus is off the DataGridView?

We are using the following event handler to alert the user if the Invoiced On is left blank:

Private Sub dataGridViewPayments_CellValidating(ByVal sender As Object, _
ByVal e As DataGridViewCellValidatingEventArgs) _
Handles DataGridViewPayments.CellValidating

    Dim headerText As String = _
        DataGridViewPayments.Columns(e.ColumnIndex).HeaderText

    ' Validate the Invoiced On cell and display the error if it's empty.
    '-------------------------------------------------------------------
    If (String.IsNullOrEmpty(e.FormattedValue.ToString()) And
        headerText.Equals("Invoiced On")) Then

        DataGridViewPayments.Rows(e.RowIndex).ErrorText = _
            "Please enter an Inoiced On date."

        e.Cancel = True
    End If
End Sub

Looks like we need a way to stop this from executing if the user simply clicks in the grid then clicks somewhere else in the form.

Upvotes: 4

Views: 994

Answers (1)

felipebueno
felipebueno

Reputation: 330

You could try something like this:

Private Sub dg_CellValidating(ByVal sender As Object, ByVal e As DataGridViewCellValidatingEventArgs) Handles dg.CellValidating
    Dim headerText As String = dg.Columns(e.ColumnIndex).HeaderText

    'Try this --------------------------------------------------------------
    Dim vClicked As Boolean = False
    If (Control.MouseButtons And MouseButtons.Left) = MouseButtons.Left Then
        vClicked = True
    End If
    '-----------------------------------------------------------------------

    'Validate the Invoiced On cell and display the error if it's empty.
    'And put vClicked here
    If Not vClicked AndAlso (String.IsNullOrEmpty(e.FormattedValue.ToString()) And headerText.Equals("Invoiced On")) Then

        dg.Rows(e.RowIndex).ErrorText = "Please enter an Inoiced On date."

        e.Cancel = True
    End If
End Sub

Please, let me know if it helped. =)

Upvotes: 1

Related Questions