How to debug a cast execption in vb.net? - vb.net

I am getting a cast exception and I have re-written this code a large number of times. I am getting the exception on the following line:
If (CInt(hHurricaneYear) < CInt(_strYears(hAverage))) Then
And I am only getting results in the lblNumberOfHurricans. the other two labels are not showing any results. I thought I was getting it when the cast exception showed up.
Can anyone suggest how to get the results and stop the exception?
Here is what I have so far (well at least the last try).
Option Strict On
Public Class frmHurricaneStatistics
' Class level Private variables.
Public Shared _intSizeOfArray As Integer = 20
Private _strYears(_intSizeOfArray) As String
Private _intNumberOfHurricans(_intSizeOfArray) As Integer
Private Sub frmHurricaneStatistics_Load(sender As Object, e As EventArgs
) Handles MyBase.Load
' This load event reads the inventory text file and fills
' the ComboBox object with the Hurricane Statistics.
' Initialize an instace of the streamreader object and declare variables.
Dim objReader As IO.StreamReader
Dim strHurricaneStatistics As String = "Hurricanes.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Please restart the
application when the file is available."
' Verify the Hurricane.txt file exists.
If IO.File.Exists(strHurricaneStatistics) Then
objReader = IO.File.OpenText(strHurricaneStatistics)
' Read the file line by line until the file is completed.
Do While objReader.Peek <> -1
_strYears(intCount) = objReader.ReadLine()
_intNumberOfHurricans(intCount) = Convert.ToInt32(objReader.ReadLine())
intCount += 1
Loop
objReader.Close()
' The ComboBox objext is filled with the Years for Hurricanes.
For intFill = 0 To (_strYears.Length - 1)
cmbYears.Items.Add(_strYears(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Close()
' If ComboBox is filled then enable the Display Statistics button.
'btnDisplayStatistics.Enabled = True
End If
End Sub
Private Sub btnDisplayStatistics_Click(sender As Object, e As EventArgs
) Handles btnDisplayStatistics.Click
' This click event calls the sub procedures for the selected years and
' the number of hurricans in that year.
Dim intSelectedYear As Integer
Dim strMissingSelection As String = "Missing Selection"
Dim strSelectAYearError As String = "Please Select a Year"
' If the ComboBox object has a selection, Display Statistics.
If cmbYears.SelectedIndex >= 0 Then
intSelectedYear = cmbYears.SelectedIndex
Else
MsgBox(strSelectAYearError, , strMissingSelection)
End If
Private Sub btnDisplayStatistics_Click(sender As Object, e As EventArgs
) Handles btnDisplayStatistics.Click
' This click event calls the sub procedures for the selected years and
' the number of hurricans in that year.
Dim intSelectedYear As Integer
Dim strMissingSelection As String = "Missing Selection"
Dim strSelectAYearError As String = "Please Select a Year"
' If the ComboBox object has a selection, call the Display Statistics procedure.
If cmbYears.SelectedIndex >= 0 Then
intSelectedYear = cmbYears.SelectedIndex
Else
MsgBox(strSelectAYearError, , strMissingSelection)
End If
' This procedure MakeLabelsVisible Is called to display the labels
' And the results.
MakeLabelsVisible()
Dim hHurricaneAverage As Integer
Dim hHurricaneYear As Integer = 0
For hAverage As Integer = 0 To _strYears.Length - 1
If (CInt(hHurricaneYear) < CInt(_strYears(hAverage))) Then
hHurricaneYear = CInt(CType(CInt(_strYears(hAverage)), String))
End If
hHurricaneAverage = hHurricaneAverage + CInt((_strYears.ToString))
hHurricaneAverage = CInt(hHurricaneAverage / _strYears.Length)
Next
' Display the statistics for the Storm Average in the selected Year
' and the most active year within the range of year.
lblNumberOfHurricanes.Text = "The Number of Hurricanes in the Year " &
_strYears(intSelectedYear) & " is " & _intNumberOfHurricans(intSelectedYear).ToString() & "."
lblAvergeNumberHurricanes.Text = "The Average Number of Storms was " &
hHurricaneAverage & " Hurricanes."
Dim intSizeOfArray As Integer = Nothing
lblMostStorms.Text = "The Year "(CInt(_strYears(CInt(hHurricaneYear.ToString())) & "
Had The Most Storms Between " & (_strYears(0) & _strYears(20).ToString)))
End Sub
Option strict on

Your error lies in that you are trying to convert an entire string array into an integer:
hHurricaneAverage = hHurricaneAverage + CInt((_strYears.ToString))
You will need to call the index of _strYears:
hHurricaneAverage = hHurricaneAverage + CInt((_strYears(hAverage).ToString))
This will also explain why the other labels do not update, because hHurricanAverage never gets calculated.

Related

How to use a loop to print a statement a number of times defined by user inputs on visual basic

I would like to make a simple program that does the following
Takes a text input of a string and the number of times it needs to be looped by the program user and produces that loop to output that string the number of times stated. My loop isn't doing that. (New to visual basic loops)
Kindly correct advise where i have gone wrong below:
Public Class Form1
Private Sub cmdLoop_Click(sender As Object, e As EventArgs) Handles cmdLoop.Click
Dim newput As String
Dim numberr As Integer
Dim counter As Integer
newput = txtStatement.Text
numberr = TxtRepeatNum.Text
For counter = 1 To numberr
lbloutput.Text = newput & vbCrLf
Next
End Sub
Your loop is writing numberr times the same string into the text box, with every iteration it overwrites the previous content. Change it to
lbloutput.Text = ""
For counter = 1 To numberr
lbloutput.Text = lbloutput.Text & newput & vbCrLf
Next

How to display the labels for this Microsoft Visual Studio code?

I'm currently taking a basic Microsoft Visual Studio 2017 course. The question asks me to import and read the contents from a text file to calculate and display the energy cost savings for a smart home. I am stuck starting on the comment, ' The formula for the average monthly savings inside the loop to repeat the process' on line 96 where I am supposed to calculate the average formula for the energy savings. I would also like to know how I can display the three labels. The name of the text formula is savings.txt. These are its contents:
January
38.17
February
41.55
March
27.02
April
25.91
May
3.28
June
18.08
July
45.66
August
16.17
September
3.98
October
17.11
November
25.78
December
51.03
Are there any additional changes I can make to improve my code? I am new to this course and welcome any suggestions or examples.
Here is also a link to my rubric. Please let me know if you cannot access its contents:
https://maricopa-my.sharepoint.com/:w:/g/personal/ric2084617_maricopa_edu/ETNr_-i-wllOr9zsRiNTyMIBG0CcNO1xICcaYVYmgKl7YA?e=tLq4Ng
I am certain I have the required variables declared. I am at a loss of how to apply them into the average formula. Should I add each of the costs from the text file or is there a more simple yet basic method to add them?
' Program Name: Smart Home Electric Savings
' Author: Richard Lew
' Date: October 27, 2019
' Purpose: This Windows application opens a text file that lists the monthly savings of a smart home's electric bill in comparison to a previous year
' without smart device activation. A smart thermostat, lighting system, and water heater were installed one year ago and the text file lists
' the savings each month. The The user selects a month read from the text file and displays that month's electric bill savings. A Button object
' displays the average monthly savings with the smart home devices and the month with the most significant savings.
Option Strict On
Public Class frmSavings
' Class Level Private variables
Private _intMonthsOfSmartSavings As Integer = 12
Public Shared _intSizeOfArray As Integer = 7
Public Shared _strSavings(_intSizeOfArray) As String
Private _strSavingsMonth(_intSizeOfArray) As String
Private _decInitialBill(_intSizeOfArray) As Decimal
Private _intMonth(_intSizeOfArray) As Integer
Private Sub fromSavings_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' The frmSavings load event reads the savings text file and fills the label objects with the savings.
' Initialize an instance of the StreamReader object and declare variables
Dim objReader As IO.StreamReader
Dim strLocationAndNameOfFile As String = "D:\CIS 159\VB_Student_Data_Files\Chapter 8\savings.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Restart when the file is available."
' Verify the file exists
If IO.File.Exists(strLocationAndNameOfFile) Then
objReader = IO.File.OpenText(strLocationAndNameOfFile)
' Read the file line by line until the file is completed
Do While objReader.Peek <> -1
_strSavings(intCount) = objReader.ReadLine()
_strSavingsMonth(intCount) = objReader.ReadLine()
_decInitialBill(intCount) = Convert.ToDecimal(objReader.ReadLine())
_intMonth(intCount) = Convert.ToInt32(objReader.ReadLine())
intCount += 1
Loop
objReader.Close()
' The Monthly Savings Combo Box object is filled with the months of the savings
For intFill = 0 To (_strSavingsMonth.Length - 1)
cboMonthSavings.Items.Add(_strSavingsMonth(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Close()
End If
End Sub
Private Sub BtnDisplayStatistics_Click(sender As Object, e As EventArgs) Handles btnDisplayStatistics.Click
' The btnDisplayStatistics click event calls the savings Sub procedures
' Declare variables
Dim intSelectedMonth As Integer
Dim strMissingSelection As String = "Missing Selection"
Dim strSelectedMonthError As String = "Select a Month"
Dim strSelectedMonth As String = ""
Dim intMonthChoice As Integer
Dim blnMonthIsSelected As Boolean = False
' If the Month Savings Combo Box is selected, then display the statistics
If cboMonthSavings.SelectedIndex >= 0 Then
intSelectedMonth = cboMonthSavings.SelectedIndex
Else
MsgBox(strSelectedMonthError, , strMissingSelection)
End If
End Sub
Private Sub MonthSavingsComboBox(ByVal intMonth As Integer)
' This Sub procedure computes and displays the savings for the month selected
' Declare variables
Dim intDoublePresentMonth As Integer
Dim decDoubleAverage As Decimal = 0
Dim decDoublePresentMonthValue As Decimal = 0
Dim decDoubleSavings As Decimal
Dim decAverageSavings As Decimal
Dim decTotal As Decimal
Dim decDoubleTotal As Decimal = 0.0D
Dim strPresentSavingsMonth As String = ""
Dim strPresentSavingsMonthValue As String = ""
Dim decSavingsMonth As Decimal
Dim strMonthOfSavings As String = ""
Dim decAverageSavingsOfMonth As Decimal
Dim decSignificantSavingsOfMonth As Decimal
Dim strMonthOfSignificantSavings As String = ""
' The procedure MakeObjectsVisible is called to display the Form objects
MakeObjectsVisible()
'Display the values and quantity of the selected values
lblDisplayMonthSavings.Text = "The electric savings for " & strPresentSavingsMonth & " is " & _strSavings(intMonth)
lblDisplayAverageMonthlySavings.Text = "The average monthly savings: " & decAverageSavings.ToString("C0")
lblDisplayMonthMostSignificantSavings.Text = _decInitialBill(intMonth) & " had the most significant monthly savings"
' The loop repeats for the life of the values
For intDoublePresentMonth = 1 To _intMonthsOfSmartSavings
' The formula for the average monthly savings inside the loop to repeat the process
decAverageSavings = decDoubleTotal / _intMonthsOfSmartSavings
' Displays the savings amounts
cboMonthSavings.Items.Add(intDoublePresentMonth.ToString())
' Accumulates the total of the savings
decTotal += decDoubleSavings
Next
End Sub
Private Sub MakeObjectsVisible()
' This procedure displays the objects showing the results
lblDisplayMonthSavings.Visible = True
btnDisplayStatistics.Visible = True
lblDisplayAverageMonthlySavings.Visible = True
lblDisplayMonthMostSignificantSavings.Visible = True
' The previous data is removed
cboMonthSavings.Items.Clear()
lblDisplayMonthSavings.Text = ""
lblDisplayAverageMonthlySavings.Text = ""
lblDisplayMonthMostSignificantSavings.Text = ""
End Sub
Private Sub MnuFile_Click(sender As Object, e As EventArgs) Handles mnuFile.Click
' The mnuFile click event displays the mnuClear and and mnuExit buttons
End Sub
Private Sub MnuClear_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
' The mnuClear click event clears and resets the form
cboMonthSavings.Items.Clear()
lblDisplayMonthSavings.Text = ""
lblDisplayAverageMonthlySavings.Text = ""
lblDisplayMonthMostSignificantSavings.Text = ""
lblDisplayMonthSavings.Visible = False
lblDisplayAverageMonthlySavings.Visible = False
lblDisplayMonthMostSignificantSavings.Visible = False
End Sub
Private Sub MnuExit_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
' The mnuExit click event closes the application
Application.Exit()
End Sub
End Class

Adding 1 everytime i use button vb.net

Basically, I need 2 make a student number and after every new entry I put the student number should +1 so 20182(or 3 if male)001 will be 20182(or 3 if male)002 after I push the button and it must keep +1 but once it reaches the 10th registered student the format changes to 20182(3 if male)010.
I have done everything but make the number +1 every time I use the button
so basically the answer must be:
Student Number is 20182001
Surname , Name
contact details
but, I done everything besides the 001, 002,003 till 010 part so if anybody could help I would be thankful
Public Class Form1
Public Number As Integer = 2018000
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strSurname As String
Dim strFullName As String
Dim strContact As String
Dim strGender As String
Dim x As Integer
'IF statement'
If Me.cboGender.SelectedItem = "Female" Then
Number = 2018300
Else
End If
If Me.cboGender.SelectedItem = "Male" Then
Number = 2018200
Else
End If
'Finding The Student Number'
Dim i As Integer = 0
Do While (i < 1)
i = i + 1
Loop
If i = 201820010 Then
Number = 201800
Else
If i = 201830010 Then
Number = 201800
End if
End If
'Add Items To ListBox'
ListBox1.Items.Add("Student number: " & Number & i)
ListBox1.Items.Add(txtSurname.Text & " , " & txtFullName.Text)
ListBox1.Items.Add(txtContact.Text)
ListBox1.Items.Add("============================================")
End Sub
End Class
Not sure what your code was doing, but based on your requirements:
Public baseFemale As Integer = 20182000
Public baseMale As Integer = 20183000
Public autoNumber As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Number as Integer;
autoNumber = autoNumber + 1
If Me.cboGender.SelectedItem = "Female" Then
Number = baseFemale + autoNumber
Else
Number = baseMale + autoNumber
Else
'Add Items To ListBox'
ListBox1.Items.Add("Student number: " & Number & i)
ListBox1.Items.Add(txtSurname.Text & " , " & txtFullName.Text)
ListBox1.Items.Add(txtContact.Text)
ListBox1.Items.Add("============================================")
End Sub
Additionally you may want to check for autoNumber exceeding 999 - but I leave that as an exercise for you.

how to check checklistbox items using datagridview vb.net?

I'm just a beginner for coding and I want to programmatically check items in checklistbox using datagridview.
Data grid view values are seperated with commas like this jhon,Metilda,saman,.
Checklistbox name as chklistinput and please help me to solve this ?
'Full coding is here..............................
Private Sub TextBox10_TextChanged(sender As Object, e As EventArgs) Handles TextBox10.TextChanged
'this is ok and searching as I want
Dim SearchV As String = TextBox10.Text
SearchV = "%" + TextBox10.Text + "%"
Me.PassIssuingRecordTableAdapter.FillBy(Me.Database4DataSet.PassIssuingRecord, SearchV)
'But the problem bigins here
Dim areasback As String = DataGridView1.Rows(0).Cells(6).Value.ToString
Dim areasback1 As String() = areasback.Split(",")
For Each x In areasback1
For i = 0 To areasback.Count - 1
If chklistInput.Items(i).ToString() = x.ToString() Then
chklistInput.SetItemChecked(i, False)
End If
Next
Next
End Sub
You have to loop over chklistInput.Items.Count - 1 instead of areasback.Count - 1
use the following code:
Dim areasback As String = DataGridView1.Rows(0).Cells(6).Value.ToString
Dim areasback1 As String() = areasback.Split(",")
Dim intCount as integer = 0
For each str as string in areasback1
For intCount = 0 To chklistInput.Items.Count - 1
If chklistInput.Items(intCount).ToString() = str Then
chklistInput.SetItemChecked(intCount , True)
End If
Next
Next
chklistInput.Refresh()
Note: comparing is case sensitive

Getting wrong output in label

I have code that I have written, that has 3 labels for number of hurricanes, average hurricanes, and the year with the most hurricanes from a txt file. The code is working and the first 2 labels are displaying the correct results. However the last label is displaying the number of the year with the most hurricanes instead of the year.
Here is what I have:
Option Strict On
Public Class frmHurricaneStatistics
' Class level Private variables.
Public Shared _intSizeOfArray As Integer = 20
Private _strYears(_intSizeOfArray) As String
Private _intNumberOfHurricans(_intSizeOfArray) As Integer
Private Sub frmHurricaneStatistics_Load(sender As Object, e As EventArgs
) Handles MyBase.Load
' This load event reads the inventory text file and fills
' the ComboBox object with the Hurricane Statistics.
' Initialize an instace of the streamreader object and declare variables.
Dim objReader As IO.StreamReader
Dim strHurricaneStatistics As String = "Hurricanes.txt"
Dim intCount As Integer = 0
Dim intFill As Integer
Dim strFileError As String = "The file is not available. Please restart the
application when the file is available."
' Verify the Hurricane.txt file exists.
If IO.File.Exists(strHurricaneStatistics) Then
objReader = IO.File.OpenText(strHurricaneStatistics)
' Read the file line by line until the file is completed.
Do While objReader.Peek <> -1
_strYears(intCount) = objReader.ReadLine()
_intNumberOfHurricans(intCount) = Convert.ToInt32(objReader.ReadLine())
intCount += 1
Loop
objReader.Close()
' The ComboBox objext is filled with the Years for Hurricanes.
For intFill = 0 To (_strYears.Length - 1)
cmbYears.Items.Add(_strYears(intFill))
Next
Else
MsgBox(strFileError, , "Error")
Close()
' If ComboBox is filled then enable the Display Statistics button.
' btnDisplayStatistics.Enabled = True
End If
End Sub
Private Sub btnDisplayStatistics_Click(sender As Object, e As EventArgs
) Handles btnDisplayStatistics.Click
' This click event calls the sub procedures for the selected years and
' the number of hurricans in that year.
Dim intSelectedYear As Integer
Dim strMissingSelection As String = "Missing Selection"
Dim strSelectAYearError As String = "Please Select a Year"
' If the ComboBox object has a selection, Display Statistics.
If cmbYears.SelectedIndex >= 0 Then
intSelectedYear = cmbYears.SelectedIndex
Else
MsgBox(strSelectAYearError, , strMissingSelection)
End If
' The procedure MakeLabelsVisible Is called to display the labels
' And the results.
MakeLabelsVisible()
Dim intAverage As Double
Dim intYear As Integer
For intIndex As Integer = 0 To _intNumberOfHurricans.Length - 1
If intYear < _intNumberOfHurricans(intIndex) Then
intYear = _intNumberOfHurricans(intIndex)
End If
intAverage = intAverage + _intNumberOfHurricans(intIndex)
Next
intAverage = intAverage / _intNumberOfHurricans.Length
' Display the statistics for the Storm Average in the selected Year
' and the most active year within the range of year.
lblNumberOfHurricanes.Text = "The Number of Hurricanes in the Year " &
_strYears(intSelectedYear) & " is " & _intNumberOfHurricans(intSelectedYear).ToString() & "."
lblAvergeNumberHurricanes.Text = "The Average Number of Storms was " & FormatNumber(intAverage, 0) & " Hurricanes."
lblMostStorms.Text = "The Year " & intYear & " Had The Most Storms Between " & (
_strYears(20) & " And " & (_strYears(0).ToString))
End Sub
Private Sub MakeLabelsVisible()
' This procedure displays the labels with the calculated results
lblNumberOfHurricanes.Visible = True
lblAvergeNumberHurricanes.Visible = True
lblMostStorms.Visible = True
End Sub
Updated code.
Looks like you're just populating intYear with the number of hurricanes?
intYear = _intNumberOfHurricans(intIndex)
I can't see where you're wanting to get a year value from. Does one even exist? Please post the rest of the code
Edit:
From what I understand (correct me if I'm wrong), you want the year that had the highest number of hurricanes? If so
Try
For intIndex As Integer = 0 To _intNumberOfHurricans.Length - 1
If _intNumberOfHurricans(intIndex) = _intNumberOfHurricans.Max Then
intYear = Integer.Parse(_strYears(intIndex))
End If
intAverage = intAverage + _intNumberOfHurricans(intIndex)
Next
What I'm doing here is looking for the highest value in _intNumberOfHurricans and comparing it to the number of hurricanes in the current iteration. If they're the same, then we are at the year with the highest number of hurricanes, so we populate intYear with _strYears(but as an Integer).
This code isn't perfect. For example, if the highest amount of hurricanes is 100, but there are 2 years where there are 100 hurricanes, it will only give the latest year, not the first year there were 100 hurricanes.
Because you set;
intYear = _intNumberOfHurricans(intIndex)
Not the year, number of hurricans. That should have point to a Year property.
intYear = _intNumberOfHurricans(intIndex).Year
Hope helps.