System.InvalidCastException when textboxes are empty - vb.net

When I type in the first text box, leaving the other text boxes empty, I get this error:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll"
Public Class myProject_P2
Public Sub CostPerKWH_TextChanged(sender As Object, e As EventArgs) Handles CostPerKWH.TextChanged
Dim CostPerkwh_Value As Integer = CostPerKWH.Text
Dim Appliancekwh_Value As Integer = ApplianceKWH.Text
Dim HourPerDay_Value As Integer = HoursPerDay.Text
Dim EnergyConsumption_Value As Integer = EnergyConsumptio.Text
EnergyConsumption_Value = CostPerkwh_Value * Appliancekwh_Value * HourPerDay_Value
End Sub
End Class

I don't really know the flow of your program but if your problem is only that error stated in your question which is System.InvalidCastException then try the code I pasted below.
Before anything else, the reason why it throws that error is perhaps you typed on the first field leaving others empty which your first field was programmed that upon text change, the values of other fields will be passed on or assigned to an integer variable. Since they are empty, therefore, the value passed on were "" values or empty string values. String values assigned to an integer will surely cause an error. Try to validate before passing the values and I suggest not to put the assigning of values in your text change, rather, try adding a button and add there the codes. Upon button click, the process goes on like this:
Dim CostPerkwh_Value As Integer
Dim Appliancekwh_Value As Integer
Dim HourPerDay_Value As Integer
Dim EnergyConsumption_Value As Integer
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If IsNumeric(CostPerKWH.Text) And IsNumeric(ApplianceKWH.Text) _
And IsNumeric(HoursPerDay.Text) And IsNumeric(EnergyConsumptio.Text) Then
CostPerkwh_Value = CostPerKWH.Text
Appliancekwh_Value = ApplianceKWH.Text
HourPerDay_Value = HoursPerDay.Text
EnergyConsumption_Value = EnergyConsumptio.Text
EnergyConsumption_Value = CostPerkwh_Value * Appliancekwh_Value * HourPerDay_Value
MsgBox(EnergyConsumption_Value)
Else
MsgBox("Some inputs are not in numeric.")
End If
End Sub

another solution would be:
if TryCast(Textboxt1.text, integer) then
' do something
end if
MSDN TryCast Documentation

Related

'Conversion from string "" to type 'Double is not valid.'

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```
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

Select random element from array and display in textbox

I have a form with a button and a textbox. I also have a text file with the following contents..
Bob:Available:None:0
Jack:Available:None:0
Harry:Available:None:0
Becky:Unavailable:Injured:8
Michael:Available:None:0
Steve:Available:None:0
Annie:Unavailable:Injured:8
Riley:Available:None:0
When the user loads the form each value of the text file gets stored into an array. This works fine. What i would like to happen is when the button is pressed a random person (name) who has the value 'Available' will be retrieved from the array and displayed in the textbox.
The code i have so far (which stores each item in text file into arrays):
Public Class Form1
'define profile of person
Public Structure PersonInfo
Public name As String
Public status As String
Public status_type As String
Public monthsunavailable As Integer
End Structure
'Profile List of persons
Public Shared personInfos As New List(Of PersonInfo)() 'roster data
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'read all infomations of person from file. lines is profile array
Dim lines() As String = IO.File.ReadAllLines(filelocation)
For Each line In lines
'Parses the line string, make Person Info and add it to Person List
'split string with ":"
If line.Trim.Equals("") Then Continue For
Dim strArr() = line.Split(":")
'make Person Info
Dim pi As New PersonInfo()
pi.name = strArr(0)
pi.status = strArr(1)
pi.status_type = strArr(2)
pi.monthsunavailable = strArr(3)
'add Person Info to Person List
personInfos.Add(pi)
Next
How do i select a random name from the array and display it in a textbox?
You can use something like this. Try reading the docs!
Private Sub Button1_click (sender As Object, e As EventArgs) Handles Button1.Click
Dim r As New Random ()
Textbox1.Text = personinfos(r.Next (0,personinfos.count)).name
End Sub
Update
To select only names with status "Available"
Private Sub Button1_click (sender As Object, e As EventArgs) Handles Button1.Click
'Instantiate a new random variable
Dim r As New Random ()
'This is a LINQ query to select all items from the list where a property of the item
'(in this case , status) is equal to something.
'Try changing Available to something else and see what you get
Dim qr = From pi in personinfos
Where pi.status = "Available"
Select pi
'The following line can be simplified as follows
'Dim i As Integer = r.Next (0,qr.count)
'Dim s As String = qr (i).name
'Textbox1.Text = s
Textbox1.Text = qr(r.Next (0,qr.count)).name
End Sub

Alternative Process

I have 2 buttons and a DataGridView with 2 Columns (0 & 1).
The 1st button transfers a randomized cell from the Column(1) to a TextBox. Then, it stores that Cell in variable (a), plus the cell that opposites it in variable (b).
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim rnd As New Random
Dim x As Integer = rnd.Next(0, Form1.DataGridView1.Rows.Count)
Dim y As Integer = 1
Dim a As String = Form1.DataGridView1.Rows(x).Cells(y).Value
Dim b As String = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
The 2nd button, however, is supposed to compare if another TextBox's text has the same string variable (b) has as Strings. Now, if so, then it has to display a certain message and so on...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If TextBox4.Text = b Then '<<< ISSUE HERE!
MsgBox("Correct! ^_^")
ElseIf TextBox4.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub
The problem is that the variable (b) is surely not shared across the two "private" subs. And so, there is NOTHING to compare to in the 2nd button's sub! I presume that the solution here is to split the "randomization process" into a separate function, then execute it directly when the 1st button gets activated. Furthermore, that function's variables have to be SHARED somehow, and I certainly don't know how!
Thanks for Mr. Olivier, the code has been improved significantly! Yet, I still encounter a "wrong" comparison issue, somehow!
Dim RND As New Random
Dim x As Integer
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
Private Sub btnRoll_Click(sender As Object, e As EventArgs) Handles btnRoll.Click
x = RND.Next(0, Form1.DataGridView1.Rows.Count)
tbxRoll.Text = GetCell(x, 1)
End Sub
Private Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
If tbxSubmit.Text = GetCell(x, 0) Then
MsgBox("Correct! ^_^")
ElseIf tbxSubmit.Text = "" Then
MsgBox("You have to enter something first! O_o")
Else
MsgBox("Wrong! >,<")
End If
End Sub</code>
Well, unbelievably, I read a guide about "comparison operations" in VB.net and tried out the first yet the most primal method to compare equality - which was to use .Equals() command - and worked like a charm! Thank God, everything works just fine now. ^_^
If tbxSubmit.Text.Equals(GetCell(x, 0)) Then
Alright now... This is going to sound weird! But, following Mr. Olivier's advise to investigate "debug" the code, I rapped the string I'm trying to compare with brackets and realized that it's been outputted after a break-line space! So, I used the following function to remove the "white-space" from both of the comparison strings! And it bloody worked! This time for sure, though. ^_^
Function RemoveWhitespace(fullString As String) As String
Return New String(fullString.Where(Function(x) Not Char.IsWhiteSpace(x)).ToArray())
End Function
If RemoveWhitespace(tbxSubmit.Text) = RemoveWhitespace(GetCell(x, 0)) Then
Turn the local variables into class fields.
Dim rnd As New Random
Dim x As Integer
Dim y As Integer
Dim a As String
Dim b As String
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
x = rnd.Next(0, Form1.DataGridView1.Rows.Count)
y = 1
a = Form1.DataGridView1.Rows(x).Cells(y).Value
b = Form1.DataGridView1.Rows(x).Cells(y - 1).Value
TextBox3.Text = a
End Sub
These fields can now be accessed from every Sub, Function and Property.
Of course Button3_Click must be called before Button2_Click because the fields are initialized in the first method. If this is not the case then you should consider another approach.
Create a function for the Cell access
Private Function GetCell(ByVal rowIndex As Integer, ByVal cellIndex As Integer) _
As String
Return Form1.DataGridView1.Rows(rowIndex).Cells(cellIndex).Value
End Function
And then compare
If TextBox4.Text = GetCell(x, y - 1) Then
...
And don't store the values in a and b anymore. If y is always 1 then use the numbers directly.
If TextBox4.Text = GetCell(x, 0) Then
...
One more thing: give speaking names to your buttons in the properties grid before creating the Click event handlers (like e.g. btnRandomize). Then you will get speaking names for those routines as well (e.g. btnRandomize_Click).
See:
- VB.NET Class Examples
- Visual Basic .NET/Classes: Fields

parse rounds to whole

I am trying to parse a textbox.text with a input value of 15.75. Here is all the code.
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim lnVendorNo, lnInHouseID, lnInventoryPackID As Integer
Dim lcVendProdID, lcVendProdDesc, lcDeliverPack As String
Dim lnDelivPackCost, lnDelivPackCost2 As Short
Integer.TryParse(txtVendorNo.Text, lnVendorNo)
lcVendProdID = txtVendProdID.Text
Integer.TryParse(txtInHouseID.Text, lnInHouseID)
lcVendProdDesc = txtVendProdDesc.Text
lcDeliverPack = txtDeliverPack.Text
txtDeliverPackCost.Text = "15.75"
Decimal.TryParse(txtDeliverPackCost.Text, lnDelivPackCost)
' Value of lnDelivPackCost in watch window is 16 and type is short
lnDelivPackCost2 = Double.Parse(txtDeliverPackCost.Text)
' value of lnDelivPackCost2 in watch window is 16 and type is short
I have another sub with the following code that works just fine.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim value As String
Dim number As Decimal
Dim lnDelivPackCost As Decimal
' Parse a floating-point value with a thousands separator.
value = "1643.57"
If Decimal.TryParse(value, number) Then
Console.WriteLine(number) ' Value of number in watch = 1643.57
End If
txtDeliverPackCost.Text = "15.75"
Decimal.TryParse(txtDeliverPackCost.Text, lnDelivPackCost) ' Value on lnDelivPackCost in watch = 15.75D
End Sub
Can anyone tell me why the parses work on one sub and not the other sub. Is it because of parsing to integers earlier in the sub. I am going bonkers trying to figure this out. Any help would be appreciated.
Larry

Converting a combobox to int

I'm trying to convert a string from a combobox to a usable integer format
my relevant piece of code:
Dim intDays As Integer
intDays = Convert.ToInt32(cboDays.Text)
lblDays.Text = intDays
After selecting my number for days, the label should change to the value for days selected if it had successfully been converted to an integer but it did not, so I am clearly missing something
If you have your combobox set to DropDownList, then the correct code is:
lblDays.Text = CInt(cboDays.SelectedItem.ToString)
you need to use the combobox SelectedIndexChanged to do this otherwise your code will not get called.
Then your code works.
Double click there to make the event.
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboDays.SelectedIndexChanged
Dim intDays As Integer
intDays = Convert.ToInt32(cboDays.Text)
lblDays.Text = intDays
End Sub
If lstRentalType.SelectedIndex <> -1 Then
'code ......
Else
'msgbox.....
End If