Marc Kane
Marc Kane

Reputation: 13

How to compare textbox value to txt file

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim linenumber0 As Integer
    linenumber0 = 0
    Dim mass As Double
    mass = (File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)
    If (Math.Abs((cDbl(TextBox1.Text) - mass < 0.5) Then
        TextBox1.BackColor = Color.Green
    End If

Im getting an error conversing from string to double is not valid. It is probably a simple solution but i cant see it right now

Upvotes: 0

Views: 212

Answers (2)

Anu6is
Anu6is

Reputation: 2658

Your error occurs because the data read from the file is a String, however you are attempting to assign it to a variable declared as Double.
You can use TryParse to convert the String to Double, avoid errors and provide appropriate feedback.

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim lineNumber0 As Integer
    Dim mass As Double
    Dim input As Double

    If Double.TryParse(File.ReadAllLines("225.txt").ElementAt(linenumber0), mass) Then
        If Double.TryParse(TextBox1.Text, input) AndAlso Math.Abs(input - mass) < 0.5 Then
            TextBox1.BackColor = Color.Green
        End If
    Else
        'Bad file input
    End If
    '...
End Sub

Upvotes: 2

Asier Gonzalez
Asier Gonzalez

Reputation: 1

I think that when you set the value to mass is catching a String, so parse it with a simple CDbl, like this

mass = cDbl(File.ReadAllLines("225.txt").ElementAt(linenumber0).ToString)

I supose that with this fix it will works. Just in case, surround it with a TRY CATCH in case what it reads is not valid

Upvotes: 0

Related Questions