If AndAlso ignored

shawnplr

Active member
Joined
May 17, 2007
Messages
44
Programming Experience
Beginner
I am getting an error: Conversion from string "" to type 'Double' is not valid.
If any of my textboxes are blank even though I have used an if AndAlso statement.
VB.NET:
    Private Sub tbWidth_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbWidth.TextChanged
        Dim wMath = tbWidth.Text / Form1.tslblWidth.Text
        Dim hMath = Form1.tslblHeight.Text * wMath
        If Form1.tslblWidth.Text IsNot Nothing AndAlso tbWidth.Text IsNot Nothing Then
            tbHeight.Text = hMath
        End If
    End Sub
 
Last edited:
The converstion from type string to type double is because you're not casting the text properties to double before doing math on them:
VB.NET:
    Private Sub tbWidth_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbWidth.TextChanged
        Dim wMath [B]As Double[/B] = Double.Parse(tbWidth.Text) / Double.Parse(Form1.tslblWidth.Text)
        Dim hMath [B]As Double[/B]= Double.Parse(Form1.tslblHeight.Text) * wMath
        If Form1.tslblWidth.Text IsNot Nothing AndAlso tbWidth.Text IsNot Nothing Then
            tbHeight.Text = hMath[B].ToString()[/B]
        End If
    End Sub
As for the AndAlso part being skipped, it's because AndAlso uses short circuit logic, meaning if the first part is false, then it skips checking the 2nd part because the thing's already wrong. You should be using .Text.Trim <> String.Empty instead of .Text IsNot Nothing:
VB.NET:
    Private Sub tbWidth_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles tbWidth.TextChanged
        If Form1.tslblWidth.Text.Trim <> String.Empty AndAlso tbWidth.Text.Trim <> String.Empty Then
            Dim hMath As Double = Double.Parse(Form1.tslblHeight.Text.Trim) * (Double.Parse(tbWidth.Text.Trim) / Double.Parse(Form1.tslblWidth.Text.Trim))
            tbHeight.Text = hMath.ToString("n")
        End If
    End Sub
 
I am getting an error ... even though I have used an if AndAlso statement.

:eek:

Unfortunately, you've forgotten to use the Option Strict On statement, which would show you that 3 lines of your code are technically invalid. I'm not surprised you are suffering errors.

Investigate Double.TryParse (or Convert.ToDouble within a Try..Catch)
 
Last edited:
Back
Top