在CellValidating上更改datagriview单元格值

时间:2016-06-02 06:21:32

标签: vb.net datagridview

我想更改用户在那里输入的单元格值,并在之前进行修剪,以避免在验证之前将左右空格置于值之上。目前这是我没有此功能的代码:

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

我试图这样做,但它完全不起作用:

   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

2 个答案:

答案 0 :(得分:0)

这是错误的事件。 CellValidating用于确定单元格的内容是否有效。 CellValidatedCellLeave更适合您的情况。

答案 1 :(得分:0)

在 CellValidating 事件中,这对我有用。

//remove the event
grdDetails.CellValidating -= grdDetails_CellValidating;
//update current cell
grdDetails.CurrentCell.Value = "My New Value";
//force grid to commit update
grdDetails.EndEdit();
//rehook the event
grdDetails.CellValidating += grdDetails_CellValidating;