Variables to list box? - vb.net

taking a VB class this term and I've been stumped on a problem I'm trying to figure out. We were asked to create a price calculator for movie titles at a movie rental place. Extra credit was storing them in a list and being able to print the list. I've gotten that far and now I want to go a step further and actually add titles to that list with an attached price. I figured the easiest way to do this would probably be with arrays but I don't have much experience working with arrays.
I was thinking something along the lines of storing each title(as its added) as well as the price in a variable to give a "Movie Title - $2.93" format in every line of the list box. For the sake of this problem I'm going to just post my full source code and that might make it easier to see what I'm trying to accomplish. ANY help would be MUCH appreciated. Thanks Stack overflow community!
A screenshot of my project can be viewed here: http://puu.sh/54SgI.jpg
Public Class Form1
'globablly declared because I might use them outside of btnAdd_Click event
Const decDiscount As Double = 0.9 '1-.10 discount = .9
Const decDVD As Decimal = 2D
Const decBlueray As Decimal = 2.5D
Const decDVDNew As Decimal = 3.25D
Const decBluerayNew As Decimal = 3.5D
Dim intCount As Integer
Dim decCost, decTotal As Decimal
Dim decDayTotal As Decimal
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AcceptButton = btnAdd
End Sub
Private Sub chkDiscount_Click(sender As Object, e As EventArgs) Handles chkDiscount.Click
If chkDiscount.CheckState = 1 Then
chkDiscount.Enabled = False
End If
End Sub
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display error when no title entered
If txtAdd.Text = "" Then
MessageBox.Show("Please enter a movie title and select the appropriate item details.", "Complete details", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
listMovies.Items.Add(txtAdd.Text)
listMovies.SelectedIndex = listMovies.SelectedIndex + 1
End If
'update list
'clear txtbox
txtAdd.Text = ""
'Decision Statements to calculate correct price
If radDVD.Checked = True Then
decCost = CDec(decDVD.ToString("c"))
If chkNew.Checked = True Then
decCost = CDec(decDVDNew.ToString("c"))
End If
ElseIf radBlueray.Checked = True Then
decCost = CDec(decBlueray.ToString("c"))
If chkNew.Checked = True Then
decCost = CDec(decBlueray.ToString("c"))
End If
End If
If chkDiscount.Checked = True Then
decCost = CDec((decCost * decDiscount).ToString("c"))
End If
'display cost
txtCost.Text = CStr(CDec(decCost))
'calc total
decTotal = CDec(decTotal + decCost)
'display total
txtTotal.Text = CStr(CDec(decTotal))
'clear chkNew every item added to list
chkNew.CheckState = 0
End Sub
'Public so summary message box can access variable
Public Sub btnFinish_Click(sender As Object, e As EventArgs) Handles btnFinish.Click
'Add +1 to counter & update txtCounter
intCount = CInt(Val(intCount) + 1)
'add to day total
decDayTotal = CDec(Val(decDayTotal) + decTotal)
'Set Everything back to empty/enabled
chkDiscount.Enabled = True
chkDiscount.CheckState = 0
chkNew.CheckState = 0
txtAdd.Text = ""
txtCost.Text = ""
txtTotal.Text = ""
decTotal = 0
decCost = 0
'Instead of clearing radios each time, a more desirable result would be to have DVD always set back to the default checked radio
radDVD.Checked = True
radBlueray.Checked = False
listMovies.Items.Clear()
End Sub
Private Sub btnSummary_Click(sender As Object, e As EventArgs) Handles btnSummary.Click
If decTotal > 0 Then
MessageBox.Show("Please finish your current order before viewing a daily summary.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
MessageBox.Show(("Your total cutomer count is: " & intCount) + Environment.NewLine + ("Your total sales today is: $" & decDayTotal), "Daily Summary", MessageBoxButtons.OK)
End If
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
listMovies.Items.Remove(listMovies.SelectedItem)
End Sub

I wont go very far here because you need to do the work. But, I would start with a class:
Public Class Movie
Public Title As String = ""
Public Cost As Decimal
' prevents you from adding a movie without critical info
Public Sub New(ByVal t As String, ByVal c As Decimal)
Title = t
Cost = c
End Sub
End Class
This would hold the info on one movie title rental, and keep it together (and can be added to in order to print exactly as you showed) . The plan (to the extent I understand what you are after) would be to create one of these for each movie rented and add it to a List(Of Movie) this is more appropriate than a Dictionary in this case.
To create a movie:
Dim m As New Movie(theTitle, theCost)
Things I would do:
You did a good job of declaring numerics as numbers. Fix the code that converts it to string and back to numeric. (edit your post)
You can use the Movie Class to populate the "Shopping Cart" listbox alone; at which point, listMovies.Items would BE the extra credit List. But it wouldnt hurt to use/learn about List (Of T). (BTW, does 'print' mean to paper, on a printer?)
What are you doing with chkDiscount? If they check it, you disable it (and never enable). Did you mean to disable the New Releases check? In THAT case, arent they really a pair of radios too?
Either way, CheckChanged is a better event for evaluating and there is no reason to manually set the check state for the user that happens by itself.
Check out List(of T) and HTH

A good thing to think about when doing assignments like this (particularly when learning your first language) is to think of the algorithm (the step you need to get to your goal).
1st, determine all the steps you need to get to your goal.
2nd, and I think this is the more import point for your question, figure out what order the steps need to be in (or better yet, what order they are most efficient in).
In your case I think that you are kind of ice skating up hill by adding the name of the movie to the list first, and then trying to add the price to the line later. Unless that kind of functionality was requested as part of the assignment I would require the user to enter both the name AND the price before accepting either (just like you do with the name currently). Like thus:
If txtAdd.Text <> "" AND txtCost.Text <> "" Then 'requiring both fields to not be null
''add moive code
Else
''MessageBox.Show("Yadda Yadda Yadda")
End If
I agree with Plutonix that creating a class, while overkill in your case, is a good idea, as it will give you practice for when it WILL be appropriate. Once you have that a class of Movie, you can then create lists of Movie(s) like this:
Dim MovieList as new List(of Movie)
So then, each time you press the btnAdd button, you can pass the values to a movie AND add it to the list.
Dim m As Movie
Dim MovieList as new List(of Movie)
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
'Display error when no title entered
If txtAdd.Text <> "" And txtCost.Text <> "" Then
myMovie = New Movie(txtAdd.Text, txtCost.Text)
myMovieList.Add(myMovie)
listMovies.Items.Clear()
For Each X As Movie In myMovieList
listMovies.Items.Add(X.DisplayMovie)
Next
Else
MessageBox.Show("Please enter a movie title and select the appropriate item details.", "Complete details", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Other Code
End Sub
Note the line ListMovies.Items.Add(X.DisplayMovie) I added a function to the class Movie (seen below) so that it will do the formatting as you suggested.
Public Function DisplayMovie()
Return Title & " - $" & Cost
End Function
This will get you much of the way. Try to extrapolate what Plutonix and myself have explained to further refine your code. For instance, try encapsulating your adjusted price calculation in its own function so you can call it from anywhere.

Related

How do I add the results to the list?

I am trying to make a program that includes all the presidents and lets you search any letter or name to show the results of presidents associated with that letter or name. However, I am having trouble with actually adding them to the list. This is a class project, so the code is designed to meet requirements for that. Specifically, the part where it says
'Show the match
addPresidentsToList(presidents(idxReturned), idxReturned)
This is saying it isn't declared, but I'm not sure how to go about it.
Any tips or advice would be appreciated, thanks!
Public Class frmLab32
Const IDX_START As Integer = 0
Const IDX_END As Integer = 1
Const IDX_NAME As Integer = 2
Dim presidents() As String
Dim headerRowNeeded As Boolean
Private Sub frmLab32_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Populate array from file
presidents = IO.File.ReadAllLines("USPresWithDates.txt")
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim idxReturned As Integer = -1
Dim idxStart As Integer = 0
'remove names
lstResults.Items.Clear()
'Header row?
headerRowNeeded = True
'Search for matches
Do
idxReturned = Array.FindIndex(presidents,
idxStart,
Function(el) el.Split(","c)(IDX_NAME).ToLower.Contains(txtSearch.Text.ToLower))
'Match Found?
If idxReturned > -1 Then
'Show the match
addPresidentsToList(presidents(idxReturned), idxReturned)
'Prepare for next search
idxStart = idxReturned + 1
End If
Loop Until idxReturned = -1
'Any names found?
If lstResults.Items.Count = 0 Then
'Update counter
lblCount.Text = "0"
'Tell User
MessageBox.Show(text:="No match found",
caption:="Search Results",
buttons:=MessageBoxButtons.OK,
icon:=MessageBoxIcon.Information)
End If
End Sub
End Class
My text file looks like this.
Washington, George
Adams, John
Jefferson, Thomas
Madison, James
Monroe, James
etc.
I use default names for controls in my text program but it is much better to use descriptive name like you did.
In the Form.Load I set the MaxLength property of the TextBox to 1. This will only allow a single character to be typed in the TextBox. You could set this property in the form designer and skip this line of code. Next fill the presidents array exactly as you did.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
TextBox5.MaxLength = 1
presidents = IO.File.ReadAllLines("C:\Users\maryo\Desktop\Presidents.txt")
End Sub
Now for the search button. We need to validate the user input. A user could enter a number or punctuation character. Char https://learn.microsoft.com/en-us/dotnet/api/system.char?view=netcore-3.1#:~:text=Remarks-,.,bit%20numeric%20(ordinal)%20value. is a .net structure representing a character. It provides some interesting methods that can be helpful from time to time. Char.IsLetter() tells us (true or false) if a character is a letter. Just what we want to know. The only problem is a String is not a Char and .Text property of a TextBox is a String. Since we limited the entry to a single character we can convert this String to a Char with CChar(). If it is a letter we make the assignment to SelectedLetter otherwise we correct the user and exit the method.
Instead of all the index stuff we can use a For Each loop. It checks each element in presidents. String has a method called StartsWith. We can check each string in presidents to see if it .StartsWith the SelectedLetter. If it does, add it to the ListBox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
'Validate user input
Dim SelectedLetter As String = ""
If Char.IsLetter(CChar(TextBox5.Text)) Then
SelectedLetter = TextBox5.Text.ToUpper
Else
MessageBox.Show("Please enter a letter A - Z.", "Enter Letter")
Exit Sub
End If
For Each pres In presidents
If pres.StartsWith(SelectedLetter) Then
ListBox1.Items.Add(pres)
End If
Next
If ListBox1.Items.Count = 0 Then
'Tell User
MessageBox.Show("No match found", "Search Results")
End If
End Sub

Calculate cost of several items with tax and a discount

Can anyone help with this school task I have
The task is to ask the user for items and the cost of the items until they chose to stop. Then combine all the costs and take 20% VAT and 10% off from 2 randomly selected items.
Here is the code I have so far (I have 2 buttons and a listbox)
Public Class Form1
Dim CurrentA As Integer
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim Items(CurrentA) As String
Dim Coins(CurrentA) As Single
Dim Stay As String
CurrentA = 0
Do Until CurrentA = 20
Items(CurrentA) = InputBox("Please Enter The Item")
Coins(CurrentA) = InputBox("Please Enter The Cost Of The Item")
Stay = InputBox("Type Yes If More Items or Type No if no More")
Stay = Stay.ToLower
If Stay = "yes" Then
End If
If Stay = "no" Then
Exit Do
End If
ListBox1.Items.Add(Items(CurrentA) & " " & Coins(CurrentA))
CurrentA += 1
Loop
End Sub
End Class
First, a few comments on the code you presented.
Dim CurrentA As Integer
'An Integers default value is zero, I don't see why this is a class level variable
'always declare variables with as narrow a scope as possible
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim Items(CurrentA) As String 'Declares an Array of Type String with an Upper Bound of 0
'Upper Bound is the highest index in the array
'Arrays start with index 0
'So your array will have 1 element at index 0
Dim Coins(CurrentA) As Single
Dim Stay As String
CurrentA = 0 'unnecessary because the default of CurrentA is already 0, but OK for clarity because it could have been changed elsewhere
'This is behaving like a console application with the code repeating in a loop.
'In Windows Forms it would be more likely to do this in a button click event (btnAddItem)
Do Until CurrentA = 20
'On the first iteration CurrentA = 0
'On the second iteration CurrentA = 1 - this exceeds the size of your array
'and will cause an index out of range error
Items(CurrentA) = InputBox("Please Enter The Item")
'With Option Strict on you must change the input to a Single
Coins(CurrentA) = CSng(InputBox("Please Enter The Cost Of The Item"))
Stay = InputBox("Type Yes If More Items or Type No if no More")
Stay = Stay.ToLower 'Good! The user might no follow directions exactly
If Stay = "yes" Then
'This is kind of silly because it does nothing
End If
'Lets say I say no on the first iteration
'This avoids the index out of range error but
'nothing is added to the list because you Exit the loop
'before adding the item to the ListBox
If Stay = "no" Then
Exit Do
End If
ListBox2.Items.Add(Items(CurrentA) & " " & Coins(CurrentA))
CurrentA += 1
Loop
End Sub
We could use arrays but not knowing how many items will be added means either making the array bigger than needed or using Redim Preserve on every addition. A much better choice is a List(Of T). They work a bit like arrays but we can just add items without the ReDim stuff.
Private lstCost As New List(Of Single)
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
'Pretend this button is called btnAdd, and you have 2 test boxes
lstCost.Add(CSng(TextBox2.Text))
'The $ introduces an interpolated string. It is a step up form String.Format
ListBox2.Items.Add($"{TextBox1.Text} - {CSng(TextBox2.Text):C}") 'The C stands for currency
TextBox1.Clear()
TextBox2.Clear()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Pretend this button is called btnTotal
'Dim total As Single = (From cost In lstCost
' Select cost).Sum
Dim total As Single = lstCost.Sum
Label1.Text = total.ToString("C") 'C for Currency
End Sub

Can't reconcile votes with candidates

Good morning all,
I'm working on a voting program in Visual Basic (using Visual Studio 2013 if that makes any difference), and I can't seem to get the votes per candidate to function.
This is an assignment so I must use the listbox.DoubleClick event handler for the selected index to tally the votes.
Thus far I have written the entire program to my liking but I cannot get the votes to coincide with the candidates. I think it has to do with this block of code
Try
'Selected candidate gets a vote tallied
vote(candidateList.SelectedIndex) += 1
candidateList.SelectedIndex = -1
Catch exc As IndexOutOfRangeException
MessageBox.Show("Please click on a candidate to vote.", "Attention!")
End Try
My entire project can be seen here if needed - Voting Machine source code
Any idea what will help my program reconcile the data? Or what my error is?
Thank you!
Edit- I've gotten it mostly working now, I get an accurate number of votes per candidate, but now I need to figure out how to get both the candidate name and their total votes in the same listbox.
The above code displays the correct votes in the correct order, but if I try to add the candidateList.selectedItem into the mix it throws an invalid cast exception as the string (candidates name) cannot be converted to an integer. How do I get the selectedItem and increment the count for the selected index? I'm stuck at this point now for most of today and help would be greatly appreciated.
Thank you!
I took a look at your code. You need to initialize the "vote" array before you start using it. You have this line:
Dim vote() As Integer
Which doesn't actually initializes the array of integers. Here are some examples how you could initialize is with a length of 3 or 3 variables.
Dim vote(3) As Integer
Dim vote As Integer() = {1,2,3}
By the way, it would also be best to check that "candidateList.SelectedIndex" has an actual valid value (isn't -1).
In your code, the vote array is declared but not initialized which is causing the NullReferenceException
Please initialize the array with proper dimension, For instance you can do that in your code in "showCandidates()" function as follows,
Sub showCandidates()
'Display the candidates in the listbox and sort alphabetically by last name
Dim query = From candidate In Candidates
Let firstName = candidate.Split(" "c)(0)
Let lastName = candidate.Split(" "c)(1)
Let name = firstName & " " & lastName
Order By lastName
Select name
For Each Name As String In query
candidateList.Items.Add(Name)
Next
'Initialize the vote array.
ReDim Preserve vote(candidateList.Items.Count)
End Sub
ReDim the vote array whenever you are adding a candidate to the list box (i-e nominate candidate) otherwise you may get an IndexOutOfBounds Exception.
I figured out the solution to my problem. Many thanks to those that helped me!
Imports System.IO
Public Class Voting
Dim Candidates() As String
Dim votes() As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Get default values and views for Voting Machine
resultsList.Visible = False
candidateList.Location = New Point(143, 71)
tallyVotes.Enabled = False
resultsList.Enabled = False
Label1.Text = "Click 'Nominate Candidate' to enter a candidate, or 'Start Voting'" & vbCrLf & "to end nominations and start the voting."
End Sub
Private Sub candidateList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles candidateList.SelectedIndexChanged
End Sub
Private Sub resultsList_SelectedIndexChanged(sender As Object, e As EventArgs) Handles resultsList.SelectedIndexChanged
End Sub
Private Sub nominateCandidate_Click(sender As Object, e As EventArgs) Handles nominateCandidate.Click
'Instructions
MessageBox.Show("When finished entering candidates, simply press enter on a blank line.", "Instructions")
'Gather list of Candidates
Dim candidateName = InputBox("Enter the name of your candidate (first and last name please):", "Candidate Name", "", 500, 500)
Dim i As Integer = 0
'Loops until a null string is entered signaling the end of input
Do Until String.IsNullOrEmpty(candidateName)
ReDim Preserve Candidates(i)
Candidates(i) = candidateName
i += 1
candidateName = InputBox("Enter the name of your candidate (first and last name please):", "Candidate Name", "", 500, 500)
Loop
End Sub
Private Sub startVoting_Click(sender As Object, e As EventArgs) Handles startVoting.Click
'Disable the Nomination button
nominateCandidate.Enabled = False
'Enable the tally votes button
tallyVotes.Enabled = True
'Set the label text to give instructions for tallying votes.
Label1.Text = "Vote for a candidate by double-clicking his or her name." & vbCrLf & "End the voting by clicking on 'Tally Votes'."
'Call sub to display the candidates for voting
showCandidates()
End Sub
Private Sub tallyVotes_Click(sender As Object, e As EventArgs) Handles tallyVotes.Click
'Makes results listbox visible and moves the candidate list to the left
resultsList.Visible = True
candidateList.Location = New Point(14, 71)
'Call the sub to tally the votes and display the winner
getResults()
End Sub
Private Sub candidateList_DoubleClick(sender As Object, e As EventArgs) Handles candidateList.DoubleClick
'Selected candidate gets a vote tallied
Try
'Selected candidate gets a vote tallied
votes(candidateList.SelectedIndex) += 1
candidateList.SelectedIndex = -1
Catch exc As IndexOutOfRangeException
MessageBox.Show("Please click on a candidate to vote.", "Attention!")
End Try
End Sub
Sub showCandidates()
'Display the candidates in the listbox and sort alphabetically by last name
Dim query = From candidate In Candidates
Let firstName = candidate.Split(" "c)(0)
Let lastName = candidate.Split(" "c)(1)
Let name = firstName & " " & lastName
Order By lastName
Select name
For Each Name As String In query
candidateList.Items.Add(Name)
Next
ReDim Preserve votes(candidateList.Items.Count - 1)
End Sub
Sub getResults()
'Add the results to the Results Listbox
For Each i In votes
resultsList.Items.Add(i)
Next
'Declare Winner
Dim mostVotes As Integer = 0
For Each item In resultsList.Items
If item > mostVotes Then
mostVotes = item
End If
Next
resultsList.SelectedItem = mostVotes
candidateList.SelectedIndex = resultsList.SelectedIndex
Dim winner = candidateList.SelectedItem
MessageBox.Show("The winner is " & winner)
End Sub
End Class

Case Statement not working with String Literals

Hi all I am trying to learn VB and am having trouble with some code I am using. I would like my program to output a specific number based on if a check box is checked using case statements but my code is not working.
Public Class frmBTPW
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btncalc.Click
Dim dblhdr As Double
Dim dblfdr As Double
Dim dbltdr As Double
dblhdr = 24
dblfdr = 35
dbltdr = 50
Select Case "Power Wash Rental"
Case "Half Day Rental"
If chkhd.Checked = True Then
txtrc.Text = "poop"
End If
Case "Full Day Rental"
If chkFD.Checked = True Then
txtrc.Text = dblfdr
End If
End Select
End Sub
Private Function Button1_Click() As CheckBox
Throw New NotImplementedException
End Function
End Class
Help would be greatly appreciated.My code isn't outputting anything in the text-box.
Beyond case statements, respectfully I think you should read up on the distinction between a literal value and a variable. "Power Wash Rental" is nothing more than a series of characters, AKA a string: (In this case "P" followed by "o" etc.) Likewise, "Half Day Rental" is a series of characters, "H" followed by "a" etc.)
"Power Wash Rental" is a literal string. So is ""Half Day Rental" and of course they will never match.
Whereas:
Dim A as string
A = TextBox1.text
Now, A is a variable. It is a string which contains whatever series of characters (text) is typed into the textbox.
This is a simple way to do it.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
chkhd.tag = 24 ' store values in the check boxes
chkfd.tag = 35 ' using the tag property
chktd.tag = 50 ' and later add up the values
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btncalc.Click
dim total as double = 0
total += IF(chkhd.checked, cdbl(chkhd.tag), 0)
total += IF(chkfd.checked, cdbl(chkfd.tag), 0)
total += IF(chktd.checked, cdbl(chktd.tag), 0)
msgbox(total)
End Sub
However, I think you might want radio buttons instead of checkboxes.
Checkboxes can all be checked. Radio buttons can only have one at a time.
This solution allows you to keep your price with the checkbox -- you could do this in the form designer instead of form load.
I would recommend reading up on Case Statements. Currently you will never get anywhere as your using a string to what, nothing. You also do not need a case for this... Also if the first condition is true and the last one is as well, the last one win's for setting the text, didn't know if you had this there for a reason or not?
If chkhd.Checked = True Then
txtrc.Text = "poop"
End If
If chkFD.Checked = True Then
txtrc.Text = dblfdr
End If
As others have stated your Case statement isn't working because you are using string literals to compare "Power Wash Rental" to "Half Day Rental" which will always be false. Plutonix was also correct in saying that a ComboBox for the rental duration should be used. The only reason not to be is if you were calculating cumulative rental days/amounts; however in that situation you should be using some sort of NumericUpDown for your multiplier against a time duration.
Here is an example that should help you get started. You could make the structure into a type of keyed collection or make it a wrapper class for a dictionary object which would make be easier to use in code. The following may not be exactly plug-and-play with your project, however it should help give you some ideas on how to handle the situation.
Option Strict On
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.ComboBox1.Items.AddRange({PowerWashRentals.halfDayText, PowerWashRentals.FullDayText, PowerWashRentals.TwoDayText})
AddHandler ComboBox1.SelectedValueChanged, AddressOf Me.ComboBox1_SelectedChanged
End Sub
Private Sub ComboBox1_SelectedChanged(sender As Object, e As EventArgs)
Dim cBox As ComboBox = DirectCast(sender, ComboBox)
Select Case cBox.SelectedItem.ToString
Case PowerWashRentals.halfDayText
Label1.Text = PowerWashRentals.HalfDayPrice.ToString
Case PowerWashRentals.FullDayText
Label1.Text = PowerWashRentals.FullDayPrice.ToString
Case PowerWashRentals.TwoDayText
Label1.Text = PowerWashRentals.TwoDayPrice.ToString
End Select
End Sub
End Class
Public Structure PowerWashRentals
Public Const HalfDayPrice As Double = 24
Public Const FullDayPrice As Double = 35
Public Const TwoDayPrice As Double = 50
Public Const halfDayText As String = "Half Day Rental"
Public Const FullDayText As String = "Full Day Rental"
Public Const TwoDayText As String = "Two Day Rental"
End Structure

Visual Basic Avg. Temp Calculator

Ok, so I am super new to visual basic and was not planning on taking it as a class either until they made it a requirement for me to get my technicians certificate at my community college. Literally understand the chapters I have read so far to a T, and then first homework assignment comes up and for the past few days I have been scratching my head as to why on earth it is not working. Here is what the Prof is asking.
Write a program that calculates average daily temperatures and summary statistics. The user will be prompted to enter a Fahrenheit temperature as a value with one decimal place and to select the name of the technician entering the temperature. The user will have the option to see the Celsius equivalent of the entered Fahrenheit temperature. The program will display the average temperature of all entered temperatures. The results are displayed when the user hits ENTER, uses the access key or clicks the Calculate button. The user will be given the opportunity to enter another temperature when the user hits ESC (Clear is the Cancel Button), uses the access key or clicks the Clear button. The user will exit the program by clicking the Exit button or using its access key. The Exit button will also display the summary statistics: 1) the number of temperatures entered by each technician and 2) the average temperature of all entered temperatures. Calculations should only be done if a numeric value between 32.0 and 80.0 (inclusive) degrees for temperature is entered and a technician has been selected.
The graphical side is a breeze with dragging and dropping, then naming the labels, radio buttons, etc... But now that I have assembled my code. Nothing is working. I'm frustrated, confused, and let down. I had no idea this class would be this hard. Here is what I came up with so far code wise. No error messages at all, just not getting any output pretty much.
Option Strict On
Option Strict On
Public Class Form1
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
'Clear App
txtTemp.Clear()
lblAverageTemp.Text = String.Empty
lblCelsius.Text = String.Empty
radDave.Checked = False
radJoe.Checked = False
chkCelsiusTemp.Checked = False
'New Temp Focus
txtTemp.Focus()
End Sub
Private Sub btnClose_Click(sender As Object, e As EventArgs) Handles btnClose.Click
'End app with display
MessageBox.Show("Dave entered intEntriesDave entries." & ControlChars.CrLf & "Joe entered intEntriesJoe entries." & _
ControlChars.CrLf & "The average temperature is _.", "Status")
Me.Close()
End Sub
Public Sub chkCelsiusTemp_CheckedChanged(sender As Object, e As EventArgs) Handles chkCelsiusTemp.CheckedChanged
'Convert entered Fahrenheit temp to Celsius
Dim dblCelsius As Double
dblCelsius = (CDbl(txtTemp.Text) - 32) * 5 / 9
lblCelsius.Text = CStr(dblCelsius)
End Sub
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Dim intEntriesDave As Integer = 0
Dim intEntriesJoe As Integer = 0
If radDave.Checked = True Then
intEntriesDave = +1
End If
If radJoe.Checked = True Then
intEntriesJoe = +1
End If
Dim dblAvg As Double
dblAvg = CDbl(txtTemp.Text) / intEntriesDave + intEntriesJoe
lblAverageTemp.Text = CStr(dblAvg)
End Sub
End Class
Hope I figure this out or I can get some help with it. I procrastinated of course, like the idiot I am, and it is due in 11 hours :\
Thanks in advance!
I would use a dictionary to store names along with temperatures.
Place a numericupdown control on your form for the temperature input (numTemp) and a textbox for names tbName and a label lblCelsius for output:
Public Class Form1
Dim temps As New Dictionary(Of String, List(Of Double))
Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
If numTemp.Value < 32 OrElse numTemp.Value > 80 OrElse tbName.Text = "" Then Exit Sub 'Invalid input
If temps.ContainsKey(tbName.Text) = False Then 'Name is new, create a new list entry
temps.Add(tbName.Text, New List(Of Double))
End If
temps(tbName.Text).Add(numTemp.Value) 'Append the entered temperature
lblCelsius.Text = "In celsius: " & CStr(numTemp.Value - 32) * 5 / 9 'Output the Celsius value
End Sub
Private Sub btnStats_Click(sender As Object, e As EventArgs) Handles btnStats.Click
Dim sb As New System.Text.StringBuilder 'Create the output
For Each k As String In temps.Keys
sb.AppendLine(k & ": " & temps(k).Average)
Next
lblCelsius.Text = sb.ToString
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
temps.Clear() 'Clear the database
End Sub
End Class
Basically everytime you click btnEnter you check your dictionary if the name already entered a value. If not a new entry is created with a new list and the new temperature is just added to the list.
Creating the output is then straightforward with the .Average method of the list.