Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / Languages / VB.NET / July 2007

Tip: Looking for answers? Try searching our database.

Conversion from string "" to type 'Integer' is not valid.

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Dave griffiths - 02 Jul 2007 15:30 GMT
Hi all
Using VB2005 on Vista with a Norwegian locale setup.

The test program has 3 textboxes the sum held in txt3.

Using the code below, txt2 conversion causes an error when it is left
empty. The code in txt1 works OK but I am asking is there a better way
of coding this

Public Class Main
   Dim y As Integer
   Dim x As Integer
   Private Sub txt1_LostFocus(ByVal sender As Object, ByVal e As
System.EventArgs) Handles txt1.LostFocus

       If txt1.Text = "" Then
           y = 0
       Else
           y = CInt(txt1.Text)
       End If
   End Sub

   Private Sub txt2_LostFocus(ByVal sender As Object, ByVal e As
System.EventArgs) Handles txt2.LostFocus

       ' This produces an error if txt2 is empty
       x = CInt(txt2.Text)

       txt3.Text = x + y
   End Sub
End Class

Thanks in advance.

Signature

Dave Griffiths

rowe_newsgroups - 02 Jul 2007 15:42 GMT
On Jul 2, 10:30 am, "Dave griffiths" <davegino...@nospam.hotmail.com>
wrote:
> Hi all
> Using VB2005 on Vista with a Norwegian locale setup.
[quoted text clipped - 32 lines]
> --
> Dave Griffiths

I would do this:

  If IsNumeric(txt2.Text) Then
      x = Integer.Parse(txt2.Text)
  Else
      x = 0
  End If

Or Even this:

   Dim x as Integer = 0
   Integer.TryParse(txt2.Text, x)

Thanks,

Seth Rowe
rowe_newsgroups - 02 Jul 2007 15:45 GMT
> On Jul 2, 10:30 am, "Dave griffiths" <davegino...@nospam.hotmail.com>
> wrote:
[quoted text clipped - 52 lines]
>
> Seth Rowe

I forgot to say why :-)

Using IsNumeric or TryCast will not only prevent a null string from
popping an exception, but will also stop non-integer values from
causing problems. For example, if the user enters text into the box
(you should probably disable this) or if they enter a value that is
out of range of an integer variable (though I don't think IsNumeric
will catch this, so you might go the tryparse way)

Thanks,

Seth Rowe
Tim Patrick - 02 Jul 2007 15:45 GMT
In the txt2_LostFocus event handler, you can change the assignment of "x" to:

  x = CInt(Val(txt2.Text))

although some programmers consider Val to be an unsafe alternative to actual
formal checking of the data. Also, there are some minor situations where
Val will generate an error instead of returning zero for unrecogized input.

-----
Tim Patrick - www.timaki.com
Start-to-Finish Visual Basic 2005

> Hi all Using VB2005 on Vista with a Norwegian locale setup.
>
[quoted text clipped - 24 lines]
> End Class
> Thanks in advance.
Dave griffiths - 02 Jul 2007 16:25 GMT
>Hi Tim

I have learned to stay away from Val as I live and run my software in a
non english society.

From MS
The Val function recognizes only the period (.) as a valid decimal
separator. When different decimal separators are used, as in
international applications, use CDbl or CInt instead to convert a
string to a number.

Signature

Dave Griffiths

> In the txt2_LostFocus event handler, you can change the assignment of
> "x" to:
[quoted text clipped - 38 lines]
> > End Class
> > Thanks in advance.
(O)enone - 02 Jul 2007 17:33 GMT
> From MS
> The Val function recognizes only the period (.) as a valid decimal
> separator. When different decimal separators are used, as in
> international applications, use CDbl or CInt instead to convert a
> string to a number.

Which sounds great, except that CDbl and CInt don't do the same thing as
Val. Val will read numeric data from the start of a non-numeric string and
return just the numeric part (so given the string "123ABC", Val will return
123.0 whereas CDbl and CInt will raise a type mistmatch; given "Hello World"
or "" , Val will return zero as opposed once again to a type mismatch).
Sometimes this functionality for Val is extremely useful -- although there
are other dangers (Val("1e3") returns 1000.0 rather than 1 as the "e" is
interpreted as the exponent operator).

We worked around this by writing a replacement function, taking the input
value, replacing all "thousands" separators (as defined by the locale) with
an empty string, and all "decimal" separators (again as defined by the
locale) with a period ("."). Then you can use Val() on it safely.

I think it's bizarre that Val works this way, but it does. Humpf.

Signature

(O)enone

Rory Becker - 02 Jul 2007 15:46 GMT
> Hi all Using VB2005 on Vista with a Norwegian locale setup.
>
[quoted text clipped - 24 lines]
> End Class
> Thanks in advance.

Well in a pinch you can use....
-------------------------------------------------------------
txt3.text = cint(iif(txt2.text = "", 0, txt2.text)) + y
-------------------------------------------------------------
... but at this point I would suggest that the proper way to do this would
be to create som sort of validation routine...

-------------------------------------------------------------
Public function ValidateForm(ErrorMessage as  String) as Boolean
-------------------------------------------------------------
Rory Becker - 02 Jul 2007 15:55 GMT
> x = CInt(txt2.Text)
> txt3.Text = x + y

My first reply seems to have mysteriously disappeared. so I will try again :)

Essentially I agree with Seth.

I would however suggest that for anything that might eventually be a less
than trivial form, that you should consider the creation of a function to
validate the form itself before proceeding to perform calculations based
on the data in that form.

for example
-------------------------------------------------------------
Public Function isFormValid(ByRef ErrorMessage as String) as Boolean
    If SomeBadCondition then
         ErrorMessage = "Alert User of Problem"
         Exit Sub
    End If
    If SomeOtherBadCondition then
         ErrorMessage = "Alert User of Problem2"
         Exit Sub
    End If

    Return True
End Function
-------------------------------------------------------------

Later on you can say...
-------------------------------------------------------------
Public Sub PerformCalculation
    ' check form first
    Dim TheErrorMessage as String
    If Not isFormValid(ThePotentialErrorMessage) then
         MessageBox.Show(TheErrorMessage)
         Exit Sub
    End If
    ' Now perform calculation
...
...
...
End Sub
-------------------------------------------------------------

This is probably overkill for any small calculation but on larger dataentry
forms, something like this can save you a lot of trouble.

--
Rory
Dave griffiths - 02 Jul 2007 16:31 GMT
Hi All

Thanks for so much input so quickly.

I agree with Rory that there needs to be some kind of form validation,
I was really asking the correct or should I say tidier way of
performing the conversion.

As the form uses extensive numeric textboxes I plan to create my own
class "numtext" with the information kindly supplied here to handle the
problem.

Signature

Dave Griffiths

> Hi all
> Using VB2005 on Vista with a Norwegian locale setup.
[quoted text clipped - 29 lines]
>
> Thanks in advance.
Rory Becker - 02 Jul 2007 17:04 GMT
> As the form uses extensive numeric textboxes I plan to create my own
> class "numtext" with the information kindly supplied here to handle
> the problem.

If this is a small project then go for it... there's lots of good stuff to
be leared by doing it yourself. :)

Again though if this is for a large paid project, it might be worth looking
into potentially buying in this type of functionality. especially if you
see yourself having to deal with multiple different types of formatting.
numbers dates

I use DeveloperExpress' XtraEditors but Infragistics and many other companies
have reasonably comprehensive solutions to the DataEntry problem as a whole.

There are also many good freeware options. www.CodeProject.com should have
a few examples.

Again it may be overkill. I cannot possibly tell what your situation is Re
time or money, but where possible I prefer not to reinvent the wheel and
risk making a square one :)

--
Rory
Dave griffiths - 02 Jul 2007 18:20 GMT
Thanks Rory

This is a small "free" project for a small community, I think I will
benefit more by "rolling my own" solution as I know I need the practice.

Signature

Dave Griffiths

> > As the form uses extensive numeric textboxes I plan to create my own
> > class "numtext" with the information kindly supplied here to handle
[quoted text clipped - 15 lines]
> is Re time or money, but where possible I prefer not to reinvent the
> wheel and risk making a square one :)

Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.