Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how to validate an integer value

Status
Not open for further replies.

njahnavi

Technical User
Dec 29, 2008
136
0
0
US
HI I am very very new to vb..so this might look very silly for you guys :)

I am using vb 2005 and the frame work is dot net 2.0

I have an datagrid adn I want to validate the value in it.
I want to validate it so that it will allow only the integer values not the real values or any other values...

tahnks for you support

 
IsNumeric is a start.

-I hate Microsoft!
-Forever and always forward.
-My kingdom for a edit button!
 
IsNumeric is a good start, but it will still allow some values through, like decimal numbers and scientific notation. There is a method that will work though.

Code:
If IsNumeric(YourValueHere + ".0e0") Then
  Debug.Print "You have an integer"
End If

If you want to only allow for positive integers....

Code:
If IsNumeric("-" & YourValueHere + ".0e0") Then
  Debug.Print "You have an integer"
End If

By adding a negative sign to your string, positive numbers will become negative and still pass, but negative numbers will be tested with "--2", the 2 negative symbols prevent it from passing the IsNumeric test.

Similarly, by adding .0e0 to your string, you prevent decimal numbers and scientific notation.

Make sense?

-George

"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Since you're using a DataGridView (more than likely you meant DataGridView if you're using .Net 2.0--the DataGrid still exists in .Net 2.0 but is not recommended over DataGridView in most cases), I would hope that your DataSource is typed correctly.

That being said, your DataGridView will accept only valid data by default.

Try this code on a new form:
Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dgv As New DataGridView
        dgv.Height = 100
        dgv.Width = 400
        dgv.Location = New Point(10, 10)
        Me.Controls.Add(dgv)

        'AddHandler dgv.DataError, AddressOf Me.DataGridView_DataError
        Dim dt As New DataTable
        dt.Columns.Add("IntColumn", System.Type.GetType("System.Int32"))
        dt.Columns.Add("DecColumn", System.Type.GetType("System.Decimal"))
        dgv.DataSource = dt
    End Sub

If you try to enter a decimal in the first column, you will notice you are unable to do so and you get an error message when you attempt to navigate off of the cell. My opinion is that it makes for better user interface guidelines to allow a user to type anything into a cell and then validate in a DataGrid type control, instead of restricting the specific characters which may be entered.

One thing you will notice is that the error message dialog is a bit of an eyesore. You can change the appearance of this in the DataError event handler.

Replace the code above with the following and you will see what I mean.
Code:
    Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dgv As New DataGridView
        dgv.Height = 100
        dgv.Width = 400
        dgv.Location = New Point(10, 10)
        Me.Controls.Add(dgv)
        AddHandler dgv.DataError, AddressOf Me.DataGridView_DataError
        Dim dt As New DataTable
        dt.Columns.Add("IntColumn", System.Type.GetType("System.Int32"))
        dt.Columns.Add("DecColumn", System.Type.GetType("System.Decimal"))
        dgv.DataSource = dt
    End Sub

    Private Sub DataGridView_DataError(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewDataErrorEventArgs)
        If e.ColumnIndex = 0 Then 'This represents the Integer column
            MessageBox.Show("Must be an integer.")
        ElseIf e.ColumnIndex = 1 Then 'This represents the Decimal column
            MessageBox.Show("Must be an decimal.")
        End If
    End Sub
 
Thanks guys for your support.
I want to test whether it has decimal values or not. If it has decimal values then i will have to raise an error. It just should have integers. Basically numbers from 0 to 9.

Even though I am using data grid i have to validate it and the data is being enter by user.Hope I am making sense.

I will try the suggestions you have given and update you guys...

I have done something from my logic what i have done is
I have taken the integer value and converted to string and checked if it has "." then i udnerstood it is a float value and then raised the error.Not sure if this fits the standard ..

Please give any comments os that I cna improve my skills on vb..:)

Thanks again guys
 
You could always write your own function to check if it's an integer (positive or negative), something like (bearing in mind this is just knocked together quickly and has no error handling) using Regular Expressions:
Code:
Imports System.Text.RegularExpressions

Function IsInteger(ByVal Expression As Object) As Boolean

        Dim options As RegexOptions = (RegexOptions.Multiline Or RegexOptions.IgnoreCase)

        Dim pNumericRegex As New Regex("^(-|[0-9])[0-9]{" & Expression.ToString.Length - 1 & "}")

        Dim m As Match = pNumericRegex.Match(Expression)

        If m.Success Then
            Return True
        Else
            Return False
        End If

    End Function
That will return True if it's an integer, False if it's not (it also won't check if the value is too large to be an integer in it's present state).

Hope this helps

HarleyQuinn
---------------------------------
The most overlooked advantage to owning a computer is that if they foul up there's no law against wacking them around a little. - Joe Martin

Get the most out of Tek-Tips, read FAQ222-2244 before posting.
 
If all you are doing is checking for a decimal point or not then yeah there is nothing wrong with just changing it to a string.

-I hate Microsoft!
-Forever and always forward.
-My kingdom for a edit button!
 
HarleyQuinn I have considered regular expressions however they were too hard to understand..
I have tried to read msdn material however not much use to me...


 
I'd put something like this in the CellValidating event handler:

If Not (IsNumeric(e.FormattedValue.ToString) AndAlso CInt(e.FormattedValue.ToString) = e.FormattedValue.ToString) then

' add additional validation for number range here

' handle invalid entries here
DataGridView1.Rows(e.RowIndex).ErrorText = "Value must be an integer"
e.Cancel = True

End If
 
njahnavi - I did most of my initial reading about Regular Expressions here and found it pretty useful.

Hope this helps

HarleyQuinn
---------------------------------
The most overlooked advantage to owning a computer is that if they foul up there's no law against wacking them around a little. - Joe Martin

Get the most out of Tek-Tips, read FAQ222-2244 before posting.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top