DataGridView - limit entry in field to be numeric only

Hi
This probably isn't a hard one for Experts.....how do I permit users only to enter numbers on a datagridview?  Some fields are for numbers / decimal numbers only and I don't want them entering invalid data.

Thanks
rwallacejAsked:
Who is Participating?
 
SanclerConnect With a Mentor Commented:
A problem with DataGridViews is that they are a pretty complex combination of a number of other controls.  If you are happy to leave validation until a user has finished editing, then the approach suggested by jpaulino and VBRocks is OK.  But if you want to catch errors DURING the edit, you cannot simply use the DataGridView's Key_? events because they don't get fired.  The keyboard messages are going, instead, to the subsidiary control in which the editing is taking place.  Here's an approach that I've used.

These declarations at the start of the form

    Private WithEvents thiscontrol As TextBox
    Dim oldtext As String = ""

Then make use of the EditingControlShowing event sub to "catch" edits in the column/s I am interested in: on these lines

    Private Sub dgv_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles dgv.EditingControlShowing
        If dgv.CurrentCell.ColumnIndex = <myNumericColumnIndex> Then
            thiscontrol = CType(e.Control, TextBox)
            oldtext = thiscontrol.Text
        Else
            thiscontrol = Nothing
            oldtext = Nothing
        End If
    End Sub

Then use one of the events of thiscontrol to do real-time checks: on these lines

    Private Sub thiscontrol_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles thiscontrol.TextChanged
        If Not IsNumeric(thiscontrol.Text) Then
            MsgBox("BooBoo")
            thiscontrol.Text = oldtext
        Else
            oldtext = thiscontrol.Text
        End If
    End Sub

Incidentally, I prefer this TextChanged approach to one based on Key_? events.  That's because (a) some characters are acceptable in some positions but not in others and (b) it copes with errors arising from copy and paste as well as from keystrokes.

Roger
0
 
Jorge PaulinoConnect With a Mentor IT Pro/DeveloperCommented:
rwallacej,

You can check the data after the user end edit the cell. In the datagridview cellendedit event paste this code

If Not IsNumeric(DatagridView1(e.ColumnIndex, e.RowIndex).Value) Then
  DatagridView1(e.ColumnIndex, e.RowIndex).Value = ""
End If

jpaulino

0
 
VBRocksCommented:
Only one comment on that code, and that is that you may need to check for a particular column, rather
than checking every column, becuase you may have some columns that allow text, for example:

If e.ColumnIndex = 1 OrElse e.ColumnIndex = 2 then

  'jpaulino's code
  If Not IsNumeric(DatagridView1(e.ColumnIndex, e.RowIndex).Value) Then
    DatagridView1(e.ColumnIndex, e.RowIndex).Value = ""
  End If

end if

0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

 
srinivasbnConnect With a Mentor Commented:
Hi

You can get the it by writing the code in Keydown or Keypress event. Suppose you want to restrict the numeric values for 2nd column in the datagridview then write the code in Keypress event for that datagridview with the following condition.

If dgvsample.currentcell.columnindex=2 then
         if isnumeric(dgvsample.item(2,1).value) then
           'At this level write your code. Or take a variable globally and set some value
           'which will tell you that it is non numeric. and in cellvalidating event for datagridview
           'do it as e.cancel as True. So that your keys pressed will be treated as null
        end if
end if
0
 
SanclerCommented:
Why does it always look different when you press the Submit button? ;-(

In the second sub

            oldtext = Nothing

should really be

            oldtext = ""

Roger
0
 
rwallacejAuthor Commented:
hi all

thank-you for your contributions.

Sancler: I like this idea. It follows what I've read elsewhere about DataGridView's Key_? events not being don't get fired

I have tried this method to handle DataGridView1. When the user enters invalid entry
The problem is now "The following exception occured in the datagridview.
System.formatexception: Input string not in a correct format.......please handle the DataError Event
0
 
SanclerCommented:
It sounds like the IsNumeric test in my example code is not enough for your context.

Please can you give a specific example of it going wrong?  What is the datatype of the column concerned?  What, if any, formatting is applied to it?  What was the invalid data that was accepted by the editing control but that is producing an error when it is committed to the cell itself?

Roger
0
 
rwallacejAuthor Commented:
datagridview is bound to a dataset
in the XSD the datatype of column is System.double

the error occurs whenever I try to move off of field that contains text,  e.g. "a"

when I insert a debug line, it does not reach  "dgv_EditingControlShowing"

when an invalid entry is entered like "a" is entered

it only reaches "dgv_EditingControlShowing" when a VALID number is entered
0
 
SanclerCommented:
How does the "a" get into the cell if the user does not type it there?  And (this is what I don't understand at the moment) how does the user type it there if the editing control is not showing?

What's the EditMode setting for your datagridview?   I've just tested with a variety of setting and data and had no problem.  But let me know what yours is so I can look specifically at that.

And can you please post the exact code (including the debug line) that you've got in the dgv_EditingControlShowing sub?  And in the TextChanged sub?

Roger
0
 
rwallacejAuthor Commented:
thanks all for the contributions.
the issue is now resolved with the help from you all.
I will split points - I trust this is OK with all
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.