3

I have a datagridview and one of the columns is a Quantity column that should only allow integers. No negative symbols or decimal points. I have prevented the user from typing in any characters but they can paste them in. I could stop this in validation but I would ideally like to not even show characters that are pasted in. How would I detect and remove pasted in letters and in what event?

Ideally I would also like for only the paste to not work, so if the field already had a 2 in it and they pasted "test" then the 2 would remain, although that isn't as important.

4

3 回答 3

1

这是一种方法:

'Set a flag to show when the form has finished initialising
Dim initialising As Boolean = True

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    'Form is initialised so set boolean to false
    initialising = False
End Sub

Private Sub DataGridView1_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
'Only process once the form is initialised as values don't exist yet!    
If Not initialising Then
        If Not IsNothing(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) Then
            'If the clipboard contains text
            If Clipboard.ContainsText Then
                ' Check to see if the value of the cell matches whats in the clipboard
                If CStr(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) = Clipboard.GetText Then
                    'You know its been pasted
                    If Not IsNumeric(CStr(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)) Then
                        'This value should be rejected
                    Else
                        'This value is allowed
                    End If
                End If
            End If
        End If
    End If
End Sub

请参阅我的注释代码以获取解释。

我不确定您是否希望在此事件上执行此操作,因为在用户离开单元格之前它不会触发该事件。但是,希望我根据剪贴板中的内容检查值的方法可以帮助您确定它是否是粘贴的值。

于 2013-05-10T15:12:57.700 回答
1

您必须实现一个验证方法并在某些DataGridView 的事件中调用它(我在想 KeyDown/Keypress 和 MouseClick)。

我认为这是不好的做法,因为您将努力寻找更多用户可以欺骗您的应用程序的方法;如今,大多数应用程序都允许用户输入他们想要的任何内容,但在用户清理输入之前,用户无法完成她的任务。大多数还提供了有关如何执行此操作的清晰屏幕说明。

于 2013-05-10T13:11:50.337 回答
0

像这样的东西

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)

End Sub
于 2013-05-10T13:11:48.850 回答