views:

1426

answers:

2

Currently I'm using:

Private Sub dgvStock_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvStock.CellEndEdit
    Select Case Me.dgvStock.Columns(e.ColumnIndex).Name
        Case "Quantity", "Unit Cost"
            If Not IsNumeric(Me.dgvStock(e.ColumnIndex, e.RowIndex).Value) Then
                Me.dgvStock(e.ColumnIndex, e.RowIndex).Value = 0
            End If
    End Select
End Sub

but is there a more elegant solution? It would be better to prevent the non-numeric input in the first place rather than fix it after entry.

+2  A: 

The solution you have posted might work better if you listened for the KeyPress event rather than the CellEndEdit event. You could then check for valid values as the user types in the text box and revert to the previous value if the entered value is not valid.

Or alternatively, and this is not exactly what you are asking for, but you could have some sort of visual indicator to tell the user what they are typing is invalid, for example changing the ForeColor to Red? This would inform the user of the bad data while not confusing him or her with a text box that refuses certain key presses. That combined with your current post entry check might be a nice solution.

John Conrad
+1  A: 

You may also set the ErrorText property of the row and check a flag or the error text at the RowValidating Event. If an error exists, set Cancel to true. Don't forget to set the errortext to an empty string when the value gets valid.

UPDATE:

I just tried this and came to better solution: Check the value in the CellValidating event and set the errortext, because here you can cancel the validation. The currently entered value can be retrieved through the property grid[e.ColumnIndex, e.RowIndex].EditedFormattedValue

H-Man2