adding contects of a text box  
Author Message
bw12117





PostPosted: Visual Basic Express Edition, adding contects of a text box Top

I'm am looking to add the contents of three textboxes (ie: 2 + 5+ 6)

However, if the textboxes are empty it will not add them and the error essage is (cannot convert string"" to double).

Do I have to use an if statement to convert the empties to "0" Or is there a different solution



Visual Studio Express Editions11  
 
 
ahmedilyas





PostPosted: Visual Basic Express Edition, adding contects of a text box Top

correct.

  • check length of textbox, if current textbox length is > 0 then check to see if the text entered is numeric (using Char.IsNumber or Char.IsDigit) and if it is, finally proceed to do some calc.

    example:

    Dim theValue as Double

    If Me.textbox1.Text.Length > 0 then

       if Double.TryParse(Me.textbox1.Text, theValue) = false then

          'error, the value entered in the textbox is not double value

       end if

    end if

     

    this would be some code which will do the above stated



  •  
     
    spotty





    PostPosted: Visual Basic Express Edition, adding contects of a text box Top

    Validate the inputs first

    Dim vara As Single

    Dim varb As Single

    If TextBox1.Text.Length = 0 Then vara = 0 Else vara = CType(TextBox1.Text, Single)

    If TextBox2.Text.Length = 0 Then varb = 0 Else varb = CType(TextBox2.Text, Single)

    Label1.Text = CType(vara + varb, String)


     
     
    ahmedilyas





    PostPosted: Visual Basic Express Edition, adding contects of a text box Top

    that would produce an error if the text entered was not of the specified type you are after... :-)

     
     
    gudel





    PostPosted: Visual Basic Express Edition, adding contects of a text box Top

    I'd probably use maskedtextbox if you're just going to have numbers in these boxes.

    Dim Box1, Box2, Box3, MySum As Double

    Try

    Box1 = CDbl(MaskedTextBox1.Text)

    Box2 = CDbl(MaskedTextBox2.Text)

    Box3 = CDbl(MaskedTextBox3.Text)

    Catch ex As InvalidCastException

    ' do nothing

    Finally

    MySum = Box1 + Box2 + Box3

    End Try

    MsgBox(MySum)

    So even if you leave one of the box empty, it'll still add the other two.