• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 305
  • Last Modified:

How to stop user from entering an invalid value on a DataGridView

Hi,

I have a DataGridView with 7 Columns.  I have set all columns to readonly = true except the last column.  The user is supposed to enter inventory counts in the last column of the dgv.  I want to validate each entry as being numeric as soon as the user enters a value.

I added code to the 'CellLeave' function and I can successfully trap the error - but how do I force the cursor back to the cell in question (I would have called this 'setfocus' in VB6).

Here is some code:

Private Sub dgvInventoryCount_CellLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvInventoryCount.CellLeave
       
 If e.ColumnIndex = 7 Then
            Dim CellValue As String = dgvInventoryCount.CurrentCell.Value.ToString
            If IsNumeric(CellValue) = False Then
                MessageBox.Show("Invalid Entry - must be a number", "Invalid Count Quantity")
                '*** WANT TO KEEP FOCUS ON THE CURRENT CELL HERE ***
            End If
End If
End Sub

As always, I'm open to attacking this from a different direction if my fundamental logic is flawed.

Thanks !
0
SteveB2175
Asked:
SteveB2175
1 Solution
 
SanclerCommented:
Have a look at the DataGridView's CellValidating event.  Setting e.Cancel = True in that should leave the focus in the cell with the invalid entry.

Roger
0
 
SteveB2175Author Commented:
That worked !!  The only other change that I had to make was that in the CellValidating event the variable 'CellValue' in my code evaluated to NULL (or nothing - don't know which).

I changed the IsNumeric check to:

If IsNumeric(e.FormattedValue) = False Then

Thanks again,

-Steve
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now