Integer Type (.net)

G

Guest

If I have a textbox, Let use to input a text.
I want to check the input text is integer type or no
I use isnum() to validate it, but double type also pass the validation.
I don't want to use Field Validation (asp.net) to check it

Any Function can check the input type is integer or not
Thank You X 100!!
 
K

Ken Cox [Microsoft MVP]

You can use Cint() for this. It will throw an OverflowException if the value
is out of range. For example, in this code try the value 2147483648 which is
one greater than the max for an integer:

Private Sub Button1_Click _
(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
Dim intTest As Integer
Try
intTest = CInt(TextBox1.Text)
Label1.Text = intTest.ToString
Catch ex As OverflowException
Label1.Text = "That was not an integer"
End Try
End Sub

<form id="Form1" method="post" runat="server">
<P>
<asp:TextBox id="TextBox1" runat="server">2147483648</asp:TextBox></P>
<P>
<asp:Button id="Button1" runat="server" Text="Button"></asp:Button></P>
<P>
<asp:Label id="Label1" runat="server"></asp:Label></P>
</form>
 
M

Morgan

Could you not use a CompareValidator and set the type to Compare(or datatype
check, can't remember the specifics) and set the datatype to Integer? That
would prevent a postback, but requires additional space in the form
designer.

Morgan
 
K

Kevin Spencer

Or, if you're using C#, you can use Convert.ToInt32(), which also works with
VB.Net.

--
HTH,
Kevin Spencer
..Net Developer
Microsoft MVP
Big things are made up
of lots of little things.
 
B

Brett J

Another way to test would be to use a regular expression. In general,
try/catch blocks shouldn't be used for controlling program flow, but in
this case it probably isn't a big deal, especially if most of the time
the numbers entered will truly be integers. If they are not and the
exception must be caught, there is a lot of overhead associated with
this. However, if only for the sake of avoiding bad habits, I would use
a regex approach. The following (C#) method should work for you:

private bool IsInteger(string test)

{
Regex reg = new Regex(@"^[-+]?[1-9]\d*$");
Match mat = reg.Match(test);
return mat.Success;
}

*NOTE:
If you don't want to accept negative numbers, remove the [-+]?
If you want to accept numbers that end with a '.0' as an integer you
could use: ^[-+]?[1-9]\d*\.?[0]*$

Regular expression curtesy of Chuck Scholton
(http://regexplib.com/REDetails.aspx?regexp_id=268)


Best,
Brett
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top