Visual Basic Confusion - vb.net

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

Related

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.

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

GPA Calculation

I'm having trouble finding out what the proper code would be to calculate the GPA. Everything I try ends up in the wrong GPA. Any help would be greatly appreciated I'm still a beginner at visual basic but this is the best I could do.
Option Explicit On
Option Strict On
Option Infer Off
Public Class mainForm
Private Sub exitButton_Click(sender As Object, e As EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub dataButton_Click(sender As Object, e As EventArgs) Handles dataButton.Click
Const Prompt As String = "Enter number of Credit Hours:"
Const Title As String = "Credit Hours"
Const Prompt2 As String = "Enter grade:"
Const Title2 As String = "Grades"
Dim inputCredit As String
Dim inputGrades As String
Dim creditHours As Integer
Dim grades As Char
Dim gradesCounter As Integer
Dim point As Integer
Dim gpaTotal As Double
Dim creditHoursAccumulator As Integer
Dim pointAccumulator As Integer
inputCredit = InputBox(Prompt, Title)
inputGrades = InputBox(Prompt2, Title2)
Do While inputCredit <> String.Empty
Integer.TryParse(inputCredit, creditHours)
Char.TryParse(inputGrades, grades)
Select Case grades
Case CChar("A")
point = 4
Case CChar("B")
point = 3
Case CChar("C")
point = 2
Case CChar("D")
point = 1
Case CChar("F")
point = 0
End Select
pointAccumulator += 1
gradesCounter += 1
creditHoursAccumulator += creditHours
inputCredit = InputBox(Prompt, Title)
inputGrades = InputBox(Prompt2, Title2)
Loop
gpaTotal = pointAccumulator / creditHoursAccumulator
totalCreditsLabel.Text = "Total credit hours:" & creditHoursAccumulator
gpaLabel.Text = "GPA:" & gpaTotal
totalGradesLabel.Text = "Number of grades entered:" & gradesCounter
End Sub
End Class
Shouldn't line:
pointAccumulator += 1
be:
pointAccumulator += point

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)

Visual Basic - Counting the occurrence of numbers from a random array

I need to use arrays and strings. The program should just search for 1 number which the user will enter (0-9). Here is my code below. It uses an array to get a random number, and it's testing the occurrences for each number. However it's not working, but I don't need it to test for every number anyway.
The program must only test for the 1 number that the user requests. So if the random number that's generated is say.. '7417', and user user has chosen '7', then the program will report back there have been two sevens. I'm going to use a textbox 'txtEnter' to get the users number to search for. Can anyone help me? Thanks!
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Randomize()
Dim ArrayNum(1) As Integer
ArrayNum(0) = Int(Rnd() * 100000)
lblDisplayNumber.Text = ArrayNum(0)
Dim num As Integer
txtEnter.Text = num
Dim counts = From c In num.ToString()
Group By c Into Group
Select DigitGroup = New With {.Count = Group.Count(),
.Digit = c, .Group = Group}
Order By DigitGroup.Count Descending
Select String.Format("There are {0} number {1}'s found.",
DigitGroup.Count, DigitGroup.Digit)
Dim message = String.Join(Environment.NewLine, counts)
End Sub
If you want to use Linq, it's short and readable:
Dim counts = From c In num.ToString()
Group By c Into Group
Select DigitGroup = New With {.Count = Group.Count(), .Digit = c, .Group = Group }
Order By DigitGroup.Count Descending
Select String.Format("There are {0} number {1}'s found.",
DigitGroup.Count, DigitGroup.Digit)
Dim message = String.Join(Environment.NewLine, counts)
Update: Here is a complete sample which shows the result of the entered number and a summary:
Dim rnd As New Random()
Dim randomInt = rnd.Next(0, 100000)
lblDisplayNumber.Text = randomInt.ToString()
Dim num As Integer
If Int32.TryParse(txtEnter.Text, num) AndAlso num >= 0 AndAlso num < 10 Then
Dim counts = From c In randomInt.ToString()
Group By c Into Group
Select DigitGroup = New With {.Count = Group.Count(), .Digit = c, .Group = Group}
Order By DigitGroup.Count Descending, DigitGroup.Digit
Dim numCount = counts.FirstOrDefault(Function(grp) grp.Digit.ToString() = num.ToString())
If numCount IsNot Nothing Then
Dim numMessage = String.Format("There are {0} number {1}'s found.", numCount.Count, num)
MessageBox.Show(numMessage)
Else
MessageBox.Show("Number does not contain " & num)
End If
Dim summaryCount = From grp In counts
Select String.Format("There are {0} number {1}'s found.", grp.Count, grp.Digit)
Dim summaryMessage = String.Join(Environment.NewLine, summaryCount)
MessageBox.Show("Summary:" & Environment.NewLine & summaryMessage)
Else
MessageBox.Show("Please enter a number between 0 and 9.")
End If
Your code has several issues, but to give you an answer directly to what is missing:
you should convert your random number to a string first
Number= Int(Rnd() * 100000)
NumberString = Number.ToString()
convert that string to an array of characters
DigitArray = NumberString.ToCharArray()
then loop over all characters of the array and convert each character c back to an integer
For Each c As Char In DigitArray
num = c - "0"C`
Then use that num as index for your counts array
count(num)+=1
instead of that horrible switch statement. I let you figure out the correct Dimstatements for those variables.
The solutions presented earlier seem a bit complicated if you just need to find how many times the entered number is in the random digits.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' create the data
Dim nDigits As Integer = 5
Dim digits(nDigits - 1) As String
For i = 0 To nDigits - 1
digits(i) = CInt(Rnd() * 10).ToString
Next
' show the data
TextBox1.Text = String.Join("", digits)
Dim inp = InputBox("Enter a number from 0 to 9")
' count the occurrences of the entered number
Dim nFound = digits.Count(Function(d) d = inp)
MsgBox(String.Format("There are {0} occurrences of {1}.", nFound, inp))
End Sub