DataGridView 只能输入整数解决方案

今天写项目功能点时,遇到一个问题,DataGridViewTextBoxColumn  只能输入数值,并且格式化为 xxxxx.xx 两位小数.

想了很多方法,但只能是输入完后才验证,后来在网上搜了一下,找到了一个好的方法,经过修改后不错,现在我把它转换为VB.NET 语言,记录下来:

Private _EditCell As DataGridViewTextBoxEditingControl = Nothing

        Private Sub dgvServices_EditingControlShowing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgvServices.EditingControlShowing
            If dgvServices.CurrentCellAddress.X = colService_Rate.Index Then
                _EditCell = CType(e.Control, DataGridViewTextBoxEditingControl)
                _EditCell.SelectAll()
                AddHandler _EditCell.KeyPress, New KeyPressEventHandler(AddressOf Me.EditCell_KeyPress)
            End If
        End Sub

        Private Sub EditCell_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
            If ((Convert.ToInt32(e.KeyChar) < 48 OrElse Convert.ToInt32(e.KeyChar) > 57) AndAlso Convert.ToInt32(e.KeyChar) <> 46 AndAlso Convert.ToInt32(e.KeyChar) <> 8 AndAlso Convert.ToInt32(e.KeyChar) <> 13) Then
                e.Handled = True
            Else
                If ((Convert.ToInt32(e.KeyChar) = 46) AndAlso CType(sender, DataGridViewTextBoxEditingControl).Text.IndexOf(".") <> -1) Then
                    e.Handled = True
                End If
            End If
        End Sub

        Private Sub dgvServices_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvServices.CellEndEdit
            If e.ColumnIndex = colService_Rate.Index AndAlso e.RowIndex > -1 Then
                dgvServices(e.ColumnIndex, e.RowIndex).Value = Math.Round(Convert.ToDecimal(dgvServices(e.ColumnIndex, e.RowIndex).Value), 2, MidpointRounding.AwayFromZero)
            End If
        End Sub

原文地址:https://www.cnblogs.com/yiwuya/p/3018957.html