How to display the labels for this Microsoft Visual Studio code? - vb.net

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

Related

If I click the calculate button the program crashes?

Just for context;
I need to calculate the average of 5 numbers located in 5 textboxes.
Nummer means number
Gemiddelde means average
and
Bereken means calculate
What is causing it to crash?
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
'Variabelen'
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + " Dit is onvoldoende"
End If
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or
nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
End Sub
I don't see what would crash the program but check to that the TextBoxes have values before assigning them to numeric variables. A Decimal value will never = "".
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click 'Variabelen'
If Not IsNumeric(txtNummer1.Text) Or _
Not IsNumeric(txtNummer2.Text) Or _
Not IsNumeric(txtNummer3.Text) Or _
Not IsNumeric(txtNummer4.Text) Or _
Not IsNumeric(txtNummer5.Text) Then
MessageBox.Show ("your mom wants you to fill in all the number boxes")
Exit Sub
End If
Dim nummer1 As Decimal = CDec(txtNummer1.Text)
Dim nummer2 As Decimal = CDec(txtNummer2.Text)
Dim nummer3 As Decimal = CDec(txtNummer3.Text)
Dim nummer4 As Decimal = CDec(txtNummer4.Text)
Dim nummer5 As Decimal = CDec(txtNummer5.Text)
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As String = (somNummers) / 5
lblGemiddelde.Text = Gemiddelde
If Gemiddelde < 5.5 Then
lblGemiddelde.Text = Gemiddelde + "Dit is onvoldoende"
End If
If nummer1 = 0 Or nummer2 = 0 Or nummer3 = 0 Or nummer4 = 0 Or nummer5 = 0 Then
butBereken.Enabled = False
MessageBox.Show ("your mom")
Else
butBereken.Enabled = True
End If
End Sub
If this doesn't work I would consider setting breakpoints in the could to determine what line is causing the crash.
If that doesn't work consider adding this line to the form's initialization:
butBereken.Caption = "Warning: Do not Click!"
Assuming the user populated all the textboxes with numeric only data, (and you have checked this) try replacing these lines in your code with this code
Dim nummer1 As Decimal = txtNummer1.Text
Dim nummer2 As Decimal = txtNummer2.Text
Dim nummer3 As Decimal = txtNummer3.Text
Dim nummer4 As Decimal = txtNummer4.Text
Dim nummer5 As Decimal = txtNummer5.Text
Dim somNummers As Decimal = nummer1 + nummer2 + nummer3 + nummer4 + nummer5
Dim Gemiddelde As Decimal = somNummers / 5
lblGemiddelde.Text = Gemiddelde.ToString("##0.0")
I'd do something more like:
Private Sub butBereken_Click(sender As Object, e As EventArgs) Handles butBereken.Click
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Dim values() As Decimal
Try
values = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim Gemiddelde As String = values.Average()
lblGemiddelde.Text = Gemiddelde & If(Gemiddelde < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
MessageBox.Show("your mom")
End Try
End Sub
I prefer this approach as it doesn't require repetitive lines of code, manually converting each TextBox to a Decimal. Since the TextBoxes are in an Array, we could also add another TextBox to the form and then add that name to the end of the Array. The rest of the code would not need to change at all; it would still just work as is.
From the Array of TextBox, we use a LINQ statement to extract the Text from each TextBox and add it to an Array of String called "inputs". From there, we convert every single String to a Decimal using Array.ConvertAll(), again avoiding repetitive code. If any of the input values is not a valid Decimal then an Exception will be thrown and we'll jump the the Catch block where the not so well written error message is displayed.
If there are no exceptions, then all String inputs were successfully converted to Decimals and stored in the "values" Array. Next we simply use the LINQ function Average() to get the average of all the values.
Lastly we display the computed average in the Label, adding the "Dit is onvoldoende" message if approapriate. The If() function used in this line is simply a shorthand version of a longer If...Else...End If statement.
In your original attempt, it looks like you wanted to disable the button if any of the values are blank (or maybe if they are invalid decimals?):
If nummer1 = "" Or nummer2 = "" Or nummer3 = "" Or nummer4 = "" Or nummer5 = "" Then
butBereken.Enabled = False
MessageBox.Show("your mom")
Else
butBereken.Enabled = True
End If
This makes no sense as if you disable the button, how would it get turned back on so that user could click it again?
A different approach would be to handle the TextChanged() event of all the TextBoxes and simply update your Label with the average in real-time whenever one of the TextBoxes is changed:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
UpdateAverage()
End Sub
Private Sub txtAll_TextChanged(sender As Object, e As EventArgs) Handles txtNummer5.TextChanged, txtNummer4.TextChanged, txtNummer3.TextChanged, txtNummer2.TextChanged, txtNummer1.TextChanged
UpdateAverage()
End Sub
Private Sub UpdateAverage()
Dim TBs() As TextBox = {txtNummer1, txtNummer2, txtNummer3, txtNummer4, txtNummer5}
Dim inputs() As String = TBs.Select(Function(x) x.Text).ToArray()
Try
Dim values() As Decimal = Array.ConvertAll(inputs, Function(s) Decimal.Parse(s))
Dim average As Decimal = values.Average
lblGemiddelde.Text = average & If(average < 5.5, " Dit is onvoldoende", "")
Catch ex As Exception
lblGemiddelde.Text = "{ Invalid Input }"
End Try
End Sub
End Class
Sample run:

How to debug a cast execption in 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.

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.

VB program to calculate grades

So I am working on a program that will ask for the number of assignments, say 20, then run through a loop that many times asking for the total points earned on each assignment as well as the total points possible to get the final grade. For example if the user put in 2 assignments with assignment 1 earning 48 points out of 50 and assignment 2 earning 35 points out of 40 the program would display the grade as 92.
So far here is what I have:
Public Class Form1
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim amountAssignments As Integer
Dim pointsEarned As Integer = 0
Dim pointsEarnedTotal As Integer = 0
Dim pointsPossible As Integer = 0
Dim pointsPossibleTotal As Integer = 0
Dim Assignment As Integer = 1
Integer.TryParse(txtAmount.Text, amountAssignments)
Do Until Assignment > amountAssignments
txtAmount.Text = String.Empty
lblAmount.Text = "Enter Points Given on Assignment " & Assignment & ":"
Integer.TryParse(txtAmount.Text, pointsEarned)
pointsEarnedTotal = pointsEarnedTotal + pointsEarned
lblAmount.Text = "Enter Points Possible on Assignment " & Assignment & ":"
Integer.TryParse(txtAmount.Text, pointsPossible)
pointsPossibleTotal = pointsPossibleTotal + pointsPossible
Assignment = Assignment + 1
Loop
lblAmount.Text = "Enter the amount of Assignments: "
lblGrade.Text = (pointsEarnedTotal / pointsPossibleTotal)
End Sub
End Class
syntax is correct but when the program is run and the number of assignments put in and calculate entered the program displays the grade as NaN with no other input requested.
Could use another set of eye(s) to look over this and tell me where i screwed up logically.
Thank you in advance!
This program seems to not have some sort of user intervention when the loop starts. What I would do is surely have the user enter the amount of assignments on the textbox and then from there would ask the user to enter marks from an input box separated by a slash e.g I enter 45/50 so after input the program finds the index of "/",all characters before the '/' are the pointsEarned and can be added to the pointsEarnedTotal while all the characters after the '/' are placed in the pointsPossible and added to the pointsPossibleTotal
Try this and tell me how it goes...give me points if it works
` Private Sub butGetMarks_Click(sender As System.Object, e As System.EventArgs) Handles butGetMarks.Click
Dim assignments As Integer = 0
Dim totalAssignments As Integer
Integer.TryParse(txtAssignments.Text, totalAssignments)
Dim pointsEarned As Double = 0
Dim pointsEarnedTotal As Double = 0
Dim possibleEarned As Double = 0
Dim possibleEarnedTotal As Double = 0
Dim temp As String
For i As Integer = 1 To totalAssignments
temp = InputBox("Enter marks per assignment separated by /")
Dim i1 As Integer
i1 = temp.IndexOf("/") 'read index of /
pointsEarned = temp.Substring(0, i1) 'read from start until / character
possibleEarned = temp.Substring(i1 + 1) 'read from after / character onwards
'add to totals
possibleEarnedTotal += possibleEarned
pointsEarnedTotal += pointsEarned
Next i
MessageBox.Show(pointsEarnedTotal & "/" & possibleEarnedTotal)
End Sub`

How to add a table from toolbox and write vb.Net code in visual studio 2012 express

I am learning VB.net. I am following Charpter 3 of Brian Siler's special edition (2001) using MS VB.net. It looks thing has been changed not too much with VB, but I met a problem in adding table from toolbox.
In the Toolbox (versions from Visual Studio 2012 Express; ASP.net 2012), to build a VB.net project, there are items like TextBox and Table. To build a web app, I can add TextBox, Label, etc and coding them without problems. However, when I add table, there is a problem.
As with Textbox and Label, I rename the table ID (to tblAmortize) first. Then I input the codes from their book, and got an error:
'tblAmortize' is not declared. It may be inaccessible due to its protection level"
As I know, the TextBox item, such as txtPrincipal.Text does not need to be declared when we use it. But it seem this "table" tblAmortize item needs to be declared first, or needs to be build up a link because tblAmortize is located in Form 2 while btnShowDetail_Click is in Form 1. The full code is as following:
Public Class Hello_Web
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim intTerm As Integer 'Term, in years
Dim decPrincipal As Decimal 'Principal amount $
Dim decIntRate As Decimal 'Interst rate %
Dim dblPayment As Double 'Monthly payment $
Dim decMonthInterest As Decimal 'Interest part of monthly payment
Dim decTotalInterest As Decimal = 0 'Total interest paid
Dim decMonthPrincipal As Decimal 'Principal part of monthly pament
Dim decTotalPrincipal As Decimal = 0 'Remaining principal
Dim intMonth As Integer 'Current month
Dim intNumPayments As Integer 'Number of monthly payments
Dim i As Integer 'Temporary loop counter
Dim rowTemp As TableRow 'Temporary row object
Dim celTemp As TableCell 'Temporary cell object
If Not IsPostBack Then 'Evals true first time browser hits the page
'SET Up THE TABLE HEADER ROW
rowTemp = New TableRow()
For i = 0 To 4
celTemp = New TableCell()
rowTemp.Cells.Add(celTemp)
celTemp = Nothing
Next
rowTemp.Cells(0).Text = "Payment"
rowTemp.Cells(1).Text = "Interest"
rowTemp.Cells(2).Text = "Principal"
rowTemp.Cells(3).Text = "Total Int."
rowTemp.Cells(4).Text = "Balance"
rowTemp.Font.Bold = True
tblAmortize.Rows.Add(rowTemp)
'PULL VALUES FROM SESSION VARIABLES
intTerm = Convert.ToInt32(Session("term"))
decPrincipal = Convert.ToDecimal(Session("Principal"))
decIntRate = Convert.ToDecimal(Session("IntRate"))
dblPayment = Convert.ToDecimal(Session("decPayment"))
'CALCULATE AMORTIZATION SCHEDULE
intNumPayments = intTerm * 12
decTotalPrincipal = decPrincipal
For intMonth = 1 To intNumPayments
'Determine Values For the Current Row
decMonthInterest = (decIntRate / 100) / 12 * decTotalPrincipal
decTotalInterest = decTotalInterest + decMonthInterest
decMonthPrincipal = Convert.ToDecimal(dblPayment) - decMonthInterest
If decMonthPrincipal > decPrincipal Then
decMonthPrincipal = decPrincipal
End If
decTotalPrincipal = decTotalPrincipal - decMonthPrincipal
'Add the values to the table
rowTemp = New TableRow()
For i = 0 To 4
celTemp = New TableCell()
rowTemp.Cells.Add(celTemp)
celTemp = Nothing
Next i
rowTemp.Cells(0).Text = intMonth.ToString
rowTemp.Cells(1).Text = Format(decMonthInterest, "$###0.00")
rowTemp.Cells(2).Text = Format(decMonthPrincipal, "$###0.00")
rowTemp.Cells(3).Text = Format(decTotalInterest, "$###0.00")
rowTemp.Cells(4).Text = Format(decTotalPrincipal, "$###0.00")
tblAmortize.Rows.Add(rowTemp)
rowTemp = Nothing
'PrevFormat()
Next intMonth
End If
End Sub
Protected Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim decPrincipal As Decimal
Dim decIntRate As Decimal
Dim intTerm As Integer, dblPayment As Double
'Store the principle in the variable decprincipal
'decPrincipal = CDbl(txtPrincipal.Text)
decPrincipal = (txtPrincipal.Text)
'Convert interest rate to its decimal equivalent
' i.e. 12.75 becomes 0.1275
decIntRate = CDbl(txtIntrate.Text) / 100
'Convert annual interest rate to monthly
' by dividing by 12 (months in a year)
decIntRate = decIntRate / 12
'Convert number of years to number of months
' by multiplying by 12 (months in a year)
intTerm = CDbl(txtTerm.Text) * 12
'Calculate and display the monthly payment.
' The format function makes the displayed number look good.
dblPayment = decPrincipal * (decIntRate / (1 - (1 + decIntRate) ^ -intTerm))
txtPayment.Text = Format(dblPayment, "$#,##0.00")
'Add Amortization Schedule
' The Schedule button will be shown only after you click the Calculate Payment LinkButton
btnShowDetail.Visible = True
End Sub
Protected Sub btnShowDetail_Click(sender As Object, e As EventArgs) Handles btnShowDetail.Click
'Storetext box values in session variables
Session.Add("Principal", txtPrincipal.Text)
Session.Add("IntRate", txtIntrate.Text)
Session.Add("Term", txtTerm.Text)
Session.Add("Payment", txtPayment.Text)
'Display the Amortization form
Response.Redirect("frmAmort.aspx")
End Sub
End Class
While you declare the table you must write runat = "Server"
This is the code sample
<Table ID = "tblMyTable" runat = "Server">
.
.
.
</Table>
Now you can use your table in code.
If you can already access the table in Form2's Code and you want it to be accessed in Form1's Code and if you don't know how to do it then here is the solution :
Dim tbl as new Table
tbl = CType(Form1.FindControl("tblMyTable"),Table)