JimmyJimm JimmyJimm - 6 months ago 27
Vb.net Question

Change datagriview cell value on CellValidating

I would like to change the value of cell value which user inputs there and do the trim before to avoid left and right spaces over value before it will be validated. Currently this is my code without this feature:

Private Sub Grid_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles Grid.CellValidating
Dim newValue = e.FormattedValue.ToString

If Not Grid.Rows(e.RowIndex).IsNewRow Then 'And Not e.RowIndex = Grid.NewRowIndex - 1 Then
Select Case e.ColumnIndex
Case 1 'Name
If String.IsNullOrEmpty(newValue) Then
e.Cancel = True
Exit Select
End If
Case Else
End Select
End If
End Sub


What I tried to do was this way, but it completely doesn't work:

Private Sub Grid_CellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles Grid.CellValidating
Dim newValue = e.FormattedValue.ToString.Trim '<---trim added

'change value of cell without trims
Dim aaa As DataGridViewCell = CType(sender, DataGridView).Rows(e.RowIndex).Cells(e.ColumnIndex)
aaa.Value = newValue


If Not Grid.Rows(e.RowIndex).IsNewRow Then 'And Not e.RowIndex = Grid.NewRowIndex - 1 Then
Select Case e.ColumnIndex
Case 1 'Name
If String.IsNullOrEmpty(newValue) Then

e.Cancel = True
Exit Select
End If
Case Else
End Select
End If
End Sub

Answer

That's the wrong event. CellValidating is for determining whether the contents of the cell is valid or not. CellValidated or CellLeave would be more suited to your situation.