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

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)

Related

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

The program will know the time span if else vb.net

I dont know how it is called thats why I called it time span.
I don't have any idea yet how to code it but this is what i want to do
Dim sy as String
If (June 2015) to (March 2016) Then
sy = "2015-2016"
End if
I know it is simple but i dont know how to code the June 2015 to 2016
Thanks in advance for the help
Edit :
Now i got to this code
I uses to do this
Dim value as DateTime = New DateTime(2017, 4, 1)
Dim value1 as DateTime = New DateTime(2018, 4, 1)
Dim sy as String
If my.computer.clock.localtime <= value then
sy = "2016-2017"
ElseIf my.computer.clock.localtime <= value1 then
sy = "2017-2018"
Else
msgbox("Check your current date")
End if
But when the computer's time changed to 2015 it shows "2016-2015"
So I use 4 textboxes to supply the data you need as variables. 2 for the years and 2 for the months. Also you need to think of how many moths left in the yeae and add the month number of the next year. If you span more than one year you have to account for this as well. O.K here is the snippet without error checking in a button event:
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Dim firstÝear As Integer = CInt(TextBox3.Text)
Dim secondYear As Integer = CInt(TextBox4.Text)
Dim firstmonthnumber As Integer = CInt(TextBox5.Text) 'months number in first year
Dim secondmonthnumber As Integer = CInt(TextBox6.Text)
Dim d1 As DateTime = New DateTime(firstÝear, firstmonthnumber, 1)
Debug.Print(d1.ToString)
Dim d2 As DateTime = New DateTime(secondYear, secondmonthnumber, 1)
Debug.Print(d2.ToString)
Dim M As Integer = Math.Abs((d1.Year - d2.Year)) - 1
Debug.Print(M.ToString)
Dim myYear As Integer = 12 - firstmonthnumber 'month left to the end of first year
Dim months As Integer = ((M * 12) + Math.Abs((d1.Month - d2.Month))) + myYear
Debug.Print(months.ToString)
End Sub

How to I make the values in the list box round to two decimal places with this visual basic code

I have written this code in visual basic to solve a basic interest calculation. The year end balances are shown in the list box and the final total is show in the label. My problem is that I can not figure out how to round the values in the list box to two decimals. I have tried various things but with no luck so far so I appreciate any help.
Public Class frmNestEgg
Private Sub btnPrincipal_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
' Declare and Initialize the variables
Dim Principal As Double = txtPrincipal.Text
Dim InterestRate As Double = txtInterestRate.Text / 100
Dim Years As Integer
Dim FinalTotal As Double
Dim YrEndAmt As Double
Years = Integer.Parse(txtYears.Text)
'Calculate the interest from the principal payment over the years input to create a total value.
For Years = 1 To Years
FinalTotal = Principal * Math.Pow((1 + InterestRate), Years)
YrEndAmt = (FinalTotal - Principal) + Principal
lstYrEndAmt.Items.Add("Year" & Years & " Balance " & YrEndAmt)
lblFinalTotal.Visible = True
lblFinalTotal.Text = FinalTotal.ToString("f1")
Next
End Sub
Private Sub frmNestEgg_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
you could use
Math.Round()
... & Math.Round(YrEndAmt, 2).ToString()
but your code had a flaw: same variable Years for looping and end condition
so change:
For Years = 1 To Years
to:
Dim Years As Integer, year As Integer
For year = 1 To Years
your entire code would then be:
Private Sub btnPrincipal_Click(sender As Object, e As EventArgs) Handles btnPrincipal.Click
Dim Principal As Double = txtPrincipal.Text
Dim InterestRate As Double = txtInterestRate.Text / 100
Dim Years As Integer, year As Integer
Dim FinalTotal As Double
Dim YrEndAmt As Double
Years = Integer.Parse(txtYears.Text)
'Calculate the interest from the principal payment over the years input to create a total value.
For year = 1 To Years
FinalTotal = Principal * Math.Pow((1 + InterestRate), Years)
YrEndAmt = (FinalTotal - Principal) + Principal
lstYrEndAmt.Items.Add("Year" & year & " Balance " & Math.Round(YrEndAmt, 2).ToString())
lblFinalTotal.Visible = True
lblFinalTotal.Text = FinalTotal.ToString("f1")
Next
End Sub

Visual Basic Confusion

I have been required to create a program that asks me to find the maximum value of one particular array. I am using multiple forms in this project and have used a user-defined data type and created multiple array under it. There is a first form that is related to this, which defines my defined data type is gStudentRecord and the arrays that define it are last name, Id, and GPA. This second form is where I write all of the code to display what I want. My question is how to get the Max GPA out of that array. I'm sorry if this isn't in very good format, this is the first time I've used Stackoverflow
Public Class frmSecond
Private Sub frmSecond_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Ctr As Integer
Dim Line As String
lstDisplay.Items.Clear()
lstDisplay.Items.Add("Name".PadRight(25) & "ID".PadRight(16) & "GPA".PadRight(20) & "Out of state".PadRight(10))
For Ctr = 0 To gIndex Step 1
Line = gCourseRoster(Ctr).LastName.PadRight(20) & gCourseRoster(Ctr).ID.PadRight(15) & gCourseRoster(Ctr).GPA.ToString.PadRight(15) & gCourseRoster(Ctr).OutOfState.ToString().PadLeft(5)
lstDisplay.Items.Add(Line)
Next
End Sub
Private Sub btnStats_Click(sender As Object, e As EventArgs) Handles btnStats.Click
Dim Ctr As Integer = 0
Dim Average As Double
Dim Sum As Double
Dim Found As Boolean = False
Dim Pass As Integer
Dim Index As Integer
lstDisplay.Items.Clear()
**For Ctr = 0 To gIndex Step 1
If gCourseRoster(Ctr).GPA > gCourseRoster(Ctr).GPA Then
lstDisplay.Items.Add(gCourseRoster(Ctr).GPA)
End If
Next**
Average = gComputeAverage(Sum)
lstDisplay.Items.Add("Number of Students: " & gNumberOfStudents)
lstDisplay.Items.Add("Average: " & Average)
End Sub
Private Function gComputeAverage(Sum As Double) As Double
Dim Ctr As Integer
Dim Average As Double
For Ctr = 0 To gIndex Step 1
Sum = Sum + gCourseRoster(Ctr).GPA
Next
Average = Sum / gNumberOfStudents
Return Average
End Function
End Class
You can use a Lambda expression to tease it out. The Cast part is converting from the gCourseRoster to a collection of Double by supplying the GPA to the Select statement.
Dim gList As New List(Of gCourseRoster)
gList.Add(New gCourseRoster With {.id = 1, .name = "Bob", .GPA = 3.9})
gList.Add(New gCourseRoster With {.id = 2, .name = "Sarah", .GPA = 3.2})
gList.Add(New gCourseRoster With {.id = 3, .name = "Frank", .GPA = 3.1})
Dim maxGPA = gList.Cast(Of gCourseRoster).Select(Function(c) c.GPA).ToList.Max
MessageBox.Show(maxGPA.ToString)
Output: 3.9

Send text from textboxes to datagrid

I have for textboxes on my form and I would like the text there to be send to a datagrid. I wrote the following:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim itemName As String = txtItem.Text
Dim qty As Double = CDbl(txtQTY.Text)
Dim price As Double = CDbl(txtPrice.Text)
Dim Total As Double = price * qty
txtTotal.Text = Convert.ToString(Total)
Dim row As Integer = grdNewInvoice.Rows.Count
Dim data As TextBox() = New TextBox() {txtItem, txtQTY, txtPrice, txtTotal}
grdNewInvoice.Rows.Add()
For i As Integer = 0 To data.Length - 1
grdNewInvoice(i, row).Value = data(0)
Next
End Sub
But I get the following on my datagrid row: System.Windows.Forms.TextBox, Text: [textbox string]
I tried the following code as well to make sure there was nothing wrong with my settings on my datagrid:
'grdNewInvoice.Rows(0).Cells(0).Value = itemName
'grdNewInvoice.Rows(0).Cells(1).Value = qty
'grdNewInvoice.Rows(0).Cells(2).Value = price
'grdNewInvoice.Rows(0).Cells(3).Value = Total
That worked fine and the text went in as expected but since I will be writing to multiple lines on the datagrid, I will need to use a loop.
What am I doing wrong here?
One way to do this is to use a list of string array.
Dim row As Integer = grdNewInvoice.Rows.Count
Dim data As New List(Of String())
data.Add({txtItem.Text, txtQTY.Text, txtPrice.Text, txtTotal.Text})
data.Add({"Item2", "qtr2", "price2", "total2"})
data.Add({"Item3", "qty3", "price3", "total3"})
For i As Integer = 0 To data.Count - 1
grdNewInvoice.Rows.Add(data(i))
Next