Reputation: 3
Just started doing Visual Basic, and am trying to make a time converter. I'm aware my code may be very inefficient or impractical, but I'm trying to make a part of the program where you type in your number of minutes into the text box as opposed to using the scrollbar. However, when the text box is empty the program crashes and throws the 'Conversion from string "" to type 'Double is not valid.' error. Code is below. The line where the error is shown is highlighted in red.
Public Class timeConverter
Private Sub scrollBar_Scroll(sender As Object, e As ScrollEventArgs) Handles scrollBar.Scroll
Dim minuteBoxInt As Integer 'Declaring variables'
Dim hourBoxInt As Integer
Dim minuteBox2Int As Integer = scrollBar.Value Mod 60
minuteBox.Text = scrollBar.Value() 'The scrollbar value will change with the minute box text'
minuteBoxInt = minuteBox.Text() 'Make the minuteBox associated with the minuteBoxInt variable'
hourBoxInt = Math.Floor(minuteBoxInt / 60) 'Rounds the decimal when the minuteBoxInt reaches 60'
hourBox.Text = hourBoxInt 'Makes the hourBox associated with the hourBoxInt variable'
minuteBox2.Text() = minuteBox2Int 'Makes the minuteBox2 associated with the minuteBox2Int variable'
End Sub
Private Sub minuteBox_TextChanged(sender As Object, e As EventArgs) Handles minuteBox.TextChanged
hourBox.Text = minuteBox.Text() / 60
End Sub
End Class```
Upvotes: 0
Views: 667
Reputation: 15091
To check user input (or lack of input) use .TryParse
. Pass it a string and a variable of the type you are looking for. The .Text
property of a TextBox
is a string and here we have declare a variable, minutes
, which will be filled with the parsed value of the string if the parse is successful. .TryParse
returns a Boolean
so it can be used in an If statement.
Private Sub minuteBox_TextChanged(sender As Object, e As EventArgs) Handles minuteBox.TextChanged
Dim minutes As Integer
If Integer.TryParse(minuteBox.Text, minutes) Then
hourBox.Text = (minutes / 60).ToString
Else
MessageBox.Show("Please make a valid entry in the minutes box.")
End If
End Sub
Upvotes: 1