[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

DataGridView - limit entry in field to be numeric only

Posted on 2007-10-01
11
Medium Priority
?
8,896 Views
Last Modified: 2008-06-17
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
0
Comment
Question by:rwallacej
10 Comments
 
LVL 48

Assisted Solution

by:jpaulino
jpaulino earned 600 total points
ID: 19992031
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
 
LVL 27

Expert Comment

by:VBRocks
ID: 19992708
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
 
LVL 5

Assisted Solution

by:srinivasbn
srinivasbn earned 600 total points
ID: 19993603
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
Industry Leaders: 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!

 
LVL 34

Accepted Solution

by:
Sancler earned 800 total points
ID: 19997205
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
 
LVL 34

Expert Comment

by:Sancler
ID: 19997217
Why does it always look different when you press the Submit button? ;-(

In the second sub

            oldtext = Nothing

should really be

            oldtext = ""

Roger
0
 

Author Comment

by:rwallacej
ID: 19997563
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
 
LVL 34

Expert Comment

by:Sancler
ID: 19997773
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
 

Author Comment

by:rwallacej
ID: 19997892
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
 
LVL 34

Expert Comment

by:Sancler
ID: 19998093
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
 

Author Comment

by:rwallacej
ID: 20151005
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

Featured Post

Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
When cloud platforms entered the scene, users and companies jumped on board to take advantage of the many benefits, like the ability to work and connect with company information from various locations. What many didn't foresee was the increased risk…
Suggested Courses

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question