如何设置DataGridView的EditingControl的值

时间:2014-12-07 13:01:57

标签: vb.net datagridview

我需要设置DataGridView.EditingControl的文本值。我试过了

myDGV.EditingControl.Text() = "1/1/2001"

myDGV.EditingControl.Text = "1/1/2001"

myDGV.EditingControl.Text("1/1/2001")

导致InvalidCastException(没有检查它只能是一个整数)。

控件没有Value()属性,所以如何设置值?

(是的,我已经确认该单元格处于编辑模式)

1 个答案:

答案 0 :(得分:1)

您需要处理EditingControlShowing事件。

Private Sub HandleDgvEditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles Dgv.EditingControlShowing
    If (TypeOf e.Control Is DataGridViewTextBoxEditingControl) Then
        With DirectCast(e.Control, DataGridViewTextBoxEditingControl)
            .Text = "1/1/2001"
        End With
    End If
End Sub

请注意,将针对所有可编辑单元格触发此事件。如果您只想操作给定列的编辑控件,则需要添加另一个条件。像这样:

If (Me.Dgv.CurrentCell.OwningColumn is Me.DgvFooColumn) Then

如果您需要从CellValidating事件恢复编辑,则在显示编辑控件时存储原始值。

Private Sub HandleDgvEditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles Dgv.EditingControlShowing

    'Cache the edit control text
    Me.cachedEditText = e.Control.Text

End Sub

Private Sub HandleDgvCellValidating(sender As Object, e As DataGridViewCellValidatingEventArgs) Handles Dgv.CellValidating

    'Ensure that the edit control exists
    If (Not Me.Dgv.EditingControl Is Nothing) Then

        'Validate the edit
        If (Not valid) Then
            Me.Dgv.EditingControl.Text = Me.cachedEditText
        End If

    End If

End Sub

Private cachedEditText As String