Results 1 to 4 of 4

Thread: Conversion error

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Feb 2007
    Posts
    65

    Conversion error

    I'm getting the error message Conversion from string "" to type 'Decimal' is not valid.
    when trying to run this code

    Call purchase.total(TextBox5.Text)

    But textbox5.Text has the 1.99. Please help?

  2. #2
    Frenzied Member stimbo's Avatar
    Join Date
    Jun 2006
    Location
    UK
    Posts
    1,739

    Re: Conversion error

    TextBoxes use Strings for the text property.

    If you want to convert a 'number' in a textbox (which is a string) you have to use something like:

    Dim item1 As Decimal = CDec(Me.TextBox1.Text)

    Or:
    vb Code:
    1. Dim item1 As Decimal = Decimal.Parse(Me.TextBox1.Text)

    (also see TryParse)
    Could have something to do with blank spaces too.
    Stim

    Free VB.NET Book Chapter
    Visual Basic 2005 Cookbook Sample Chapter

  3. #3
    PowerPoster VBDT's Avatar
    Join Date
    Sep 2005
    Location
    CA - USA
    Posts
    2,922

    Re: Conversion error

    Ues TryParse
    vb Code:
    1. Dim total As Decimal
    2.         Dim myStrTotal As String = ""
    3.         'If the myStrTotal is "" or it is some thing that
    4.         'can't be convertet to decimal than the "total" will be 0
    5.         Decimal.TryParse(myStrTotal, total)

  4. #4
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Conversion error

    You should use TryParse as VBDT suggests but it provides more than that. If you had to rely on testing the value afterwards you couldn't tell the difference between a value of zero and a failure. Normally if the operation failes you won't want to use zero, but rather notify the user of the failure and ask them to provide a valid value:
    vb Code:
    1. Dim item1 As Decimal
    2.  
    3. If Decimal.TryParse(Me.TextBox1.Text, item1) Then
    4.     'Use item1 here.
    5. Else
    6.     MessageBox.Show("Please enter a valid numerical value.")
    7. End If
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width