Click here to Skip to main content
14,689,466 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The code I used below allows me to only accept integer values in a Column on my DataGridView.

I would now like to know how can I limit it so only the numbers 1 to 5 can be entered, or a message saying "Enter a number 1 to 5" comes up.


What I have tried:

Private Sub dataGVGeneral_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles dataGVGeneral.CellValidating

If e.ColumnIndex = 3 Then
            If dataGVGeneral.IsCurrentCellDirty Then
                If Not IsNumeric(e.FormattedValue) Then
                    e.Cancel = True
                    MessageBox.Show("Please enter a Number in Priority")
                End If
            End If
        End If
End Sub
Updated 26-Jul-20 19:23pm

1 solution

Try something like:
Private Sub dataGridView1_CellValidating(ByVal sender As Object, _
    ByVal e _
    As DataGridViewCellValidatingEventArgs) _
    Handles dataGridView1.CellValidating

    Me.dataGridView1.Rows(e.RowIndex).ErrorText = ""
    Dim newInteger As Integer

    ' Don't try to validate the 'new row' until finished editing since there
    ' is not any point in validating its initial value.
    If dataGridView1.Rows(e.RowIndex).IsNewRow Then Return
    If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) OrElse (newInteger < 1 And newInteger >5) Then
        e.Cancel = True
        Me.dataGridView1.Rows(e.RowIndex).ErrorText = "the value must be an integer between 1 to 5"

    End If
End Sub

To learn and know more, have a look at the following documentations:
Validate Data in DataGridView Control - Windows Forms | Microsoft Docs[^]
DataGridView.CellValidating Event (System.Windows.Forms) | Microsoft Docs[^]
Custom Numeric Edit Elements for DataGridView[^]
Maciej Los 27-Jul-20 6:10am
Sandeep Mewara 27-Jul-20 6:16am
Richard Deeming 27-Jul-20 12:40pm
(newInteger < 1 And newInteger > 5)

That condition will never be met. There are no numbers which are both less than 1 and greater than 5 at the same time.

If Not Integer.TryParse(e.FormattedValue.ToString(), newInteger) OrElse newInteger < 1 OrElse newInteger > 5 Then
Sandeep Mewara 27-Jul-20 13:16pm
:) thanks for the catch. Yep, true. +5 to you for this virtual for now.
Sandeep Mewara 27-Jul-20 13:27pm
My intention was to write:
(newInteger >0 1 And newInteger < 6)


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900