VB.Net DataGridView将仅在编辑模式下接受数值

时间:2019-01-09 12:23:24

标签: vb.net datagridview

我的datagridview中的一个特定单元格只能在编辑模式下接受数字。 我想要的是,如果他们将单元格留空或为0,它将自动更改为值1。

以下是我的代码:

Private Sub dgvPrint_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles dgvPrint.EditingControlShowing
    Dim txtEdit As TextBox = e.Control

    RemoveHandler txtEdit.KeyPress, AddressOf CopiesText_KeyPress
    AddHandler txtEdit.KeyPress, AddressOf CopiesText_KeyPress
End Sub



Private Sub CopiesText_KeyPress(sender As Object, e As KeyPressEventArgs) Handles CopiesText.KeyPress

    If dgvPrint.CurrentCell.ColumnIndex = 5 Then
        If IsNumeric(e.KeyChar.ToString()) Or e.KeyChar = ChrW(Keys.Back) Then
            e.Handled = False
        Else
            e.Handled = True
            MessageBox.Show("Invalid input." & vbCrLf & "Please enter numeric value.", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End If
    End If

End Sub

1 个答案:

答案 0 :(得分:0)

感谢您的创意。我所做的是

Private Sub dgvPrint_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles dgvPrint.CellEndEdit
    For X = 0 To dgvPrint.Rows.Count - 1
        If Val(dgvPrint.Rows(X).Cells("dgvcCopies").Value) = 0 Then
            dgvPrint.Rows(X).Cells("dgvcCopies").Value = 1
        End If
    Next
End Sub

它正在工作,但是我不知道这是否是正确的代码。