Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One column in a vb.net Datagridview should not allow paste of non-integers

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.

like image 727
Loogawa Avatar asked Jan 26 '26 21:01

Loogawa


2 Answers

Here's one approach:

'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

See my commentated code for an explanation.

I'm not sure you will want to do it on this event as it doesn't fire the event until the user leaves the cell. Hopefully however my approach of checking the value against what is in the clipboard might help you to identify if its a pasted value.

like image 173
GeorgeK Avatar answered Jan 28 '26 15:01

GeorgeK


You'd have to implement a validating method and call it in some of the DataGridView's events (I'm thinking KeyDown/Keypress and MouseClick).

I think it's bad practice, because you'll be struggling to find more ways in which the user can trick your application; most apps nowadays let the user input whatever they want, but keep the user from completing her task until she has sanitized her input. Most also give clear on-screen instructions on how to do so.

like image 33
Geeky Guy Avatar answered Jan 28 '26 15:01

Geeky Guy