Visual Basic Avg. Temp Calculator - vb.net

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.

Related

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

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

How can I essentially stop my VB program until a valid value is entered via Text Box?

How can I work around an invalid/null value entered into a text box?
Basically I have a simple program I need to develop to solve a simple quadratic equation:
Public Class Main
Private Sub btnHelp_Click(sender As System.Object, e As System.EventArgs) Handles btnHelp.Click
UserGD.Show()
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtStepX.Text = ""
lstResult.Items.Clear()
End Sub
Private Sub cmdGo_Click(sender As System.Object, e As System.EventArgs) Handles cmdGo.Click
Do
txtStepX.Text = InputBox("Please enter a valid value for x!", "Oops!", "")
Loop While String.IsNullOrEmpty(txtStepX.Text)
Dim stepx As Single
Dim X As Single
Dim y As Single
stepx = txtStepX.Text
Dim result As String
For X = -5 To 5 Step stepx
y = (3 * (X) ^ 2) + 4
result = ("x = " & X & " >>>>>>>>>> y = " & y)
lstResult.Items.Add(result)
Next
End Sub
End Class
This is the part I want to focus on:
Do
txtStepX.Text = InputBox("Please enter a valid value for x!", "Oops!", "")
Loop While String.IsNullOrEmpty(txtStepX.Text)
Dim stepx As Single
Dim X As Single
Dim y As Single
stepx = txtStepX.Text
Dim result As String
The above manages to check the text box (after its text value is changed by the Input Box) and loops fine, as long as it is empty... However, say I put a letter in, say, "l", it crashes and Visual Studio gives me the error "Conversion from string 'l' to type 'Single' is not valid." - which is fair enough. Although, I assumed the Null in isNullorEmpty meant it would catch invalid values, such as strings when it's supposed to be single.
I've tried quite a few things, and even my Computing teacher has been trying to get a solution.
I can't remember most of the things I've tried thus far so if I'll give whatever you guys come up with a go just to be on the safe side!
Update
Although not the clearest of code - here is what I found works the best for my needs:
'Written by a very tired and frustrated Conner Whiteside
'With his own blood.
'And sweat.
'And tears.
'Lots of tears.
'28/10/2014
Public Class Main
Private Sub btnHelp_Click(sender As System.Object, e As System.EventArgs) Handles btnHelp.Click
UserGD.Show()
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtStepX.Text = ""
lstResult.Items.Clear()
End Sub
' On Go button click
Private Sub cmdGo_Click(sender As System.Object, e As System.EventArgs) Handles cmdGo.Click
'Checks if Text Box value is a number
If IsNumeric(txtStepX.Text) Then
'Declares variables if Text Box value is in fact a number
Dim result As String
Dim stepx As Double
Dim X As Double
Dim y As Double
'Displays error message with a re-input opportunity if previously entered number is out of range.
Do While txtStepX.Text <= 0 Or txtStepX.Text > 10
'InputBox simply changed the value of the TextBox's Text. MUST be an InputBox or there will be nothing to break the loop.
txtStepX.Text = InputBox("The step size for the x values must not be a negative number or above 10." & vbCrLf & "Please enter another number for the step size of the x values.", "Oops!")
'Covers an Empty input given that IsNumeric does not. This can also prevent crashing if the 'Cancel' or 'X' is pressed on InputBox.
If txtStepX.Text = "" Then
'Exits Sub Class in order to avoid running mathematical operations (below) with a string "". Effectively allows a 'reset'.
Exit Sub
End If
Loop
'After all checks, sets Text Boxvalue to variable stepx
stepx = txtStepX.Text
'Loops the solving of the equation from x = -5 to x = 5 with the specified step size.
For X = -5 To 5 Step stepx
'sets the answer of the equation (y) to variable y.
y = (3 * (X) ^ 2) + 4
'concatenates a string in the required format.
result = ("x = " & X & " >>>>>>>>>> y = " & y)
'Adds the result to the List Box before repeating the process for the next value of x.
lstResult.Items.Add(result)
Next
'Catches any non numeric inputs in the Text Box or the Input Box e.g "l".
ElseIf Not IsNumeric(txtStepX.Text) Then
'Displays error message before ending If statement and Sub Class, allowing the user to return to the start and try another input. - No Input Box or Exit Sub needed.
MsgBox("Please enter a valid number for the step size of the values of x.", 64, "Oops!")
End If
End Sub
End Class
Honestly wouldn't have gotten anywhere if it weren't for your efforts!
I would simply check if the input is numeric.
If IsNumeric(txtStepX.text) then
// Your statements
Else
// MsgBox("Please enter a number")
End if
However, it will accept something like 3.5.4
A more complicated solution would be to limit the characters from being entered by checking on each keypress,
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
If e.KeyChar <> ChrW(Keys.Back) Then
If Char.IsNumber(e.KeyChar) Then
//Statements here
Else
e.Handled = True
End If
End If
End Sub
First, I recommend that you use the Double type instead of Single - it won't make any difference to how fast your program runs, but it will reduce rounding errors a lot.
Second, you can use Double.TryParse to check if a string can be parsed as a Double value. IsNumeric has some quirks which you do not want to find out about.
I took the liberty of adjusting the text which is shown to the user, as an "Oops!" before they have even tried to enter a value might be confusing, and it is better to tell them a number is needed than "a valid value":
Dim stepx As Double
Dim inp As String = ""
Dim inputTitle As String = "Number required"
Do
inp = InputBox("Please enter a number for x:", inputTitle)
' change the input box title to indicate something is wrong - if it is shown again.
inputTitle = "Oops!"
Loop While Not Double.TryParse(inp, stepx)
txtStepX.Text = stepx.ToString()

Variables to list box?

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.

Passing arguments to methods in VB

I'm hoping you guys can help with a problem that should be simple to solve, I've just had issues finding a solution. In the program that I'm writing some of the textbox's have to be numeric between 1 and 10, and others just have to be numeric. Instead of coding each textbox to verify these parameters I decided to write methods for each of them. I'm having problems passing the arguments and getting it to function correctly. Included is some of my code that shows what I'm trying to accomplish.
Public Shared Sub checkforonetoten(ByVal onetoten As Double)
If (onetoten > 1 & onetoten < 10) Then
Else
MessageBox.Show("Please enter a Number between 1-10", "Error")
End If
End Sub
Public Shared Sub checkfornumber(numCheck As Double)
Dim numericCheck As Boolean
numericCheck = IsNumeric(numCheck)
If (numericCheck = False) Then
MessageBox.Show("Please enter a number", "Error")
End If
End Sub
Private Sub textboxS_TextChanged(sender As Object, e As EventArgs) Handles textboxS.TextChanged
Dim S As Double
S = textboxS.Text
checkfornumber(S)
checkforonetoten(S)
End Sub
One of your main problems is you're converting your text without validating it. You're also programming without the Options On to warn you of bad conversion techniques like you're using in the event handler.
The TryParse method would come in handy here:
Private Sub textboxS_TextChanged(sender As Object, e As EventArgs) Handles textboxS.TextChanged
Dim S As Double
If Double.TryParse(textboxS.Text, S) Then
checkforonetoten(S)
End If
End Sub
Since the TryParse method validates your text and sets the value to 'S', you only need to check the range.
Of course using NumericUpDown controls would make all this moot, since the values will always only be numbers and you can set the range on each one.
one way to structure it is to have one event procedure process the similar TB types:
Private Sub textboxS_TextChanged(sender As Object, e As EventArgs) _
Handles textbox1.TextChanged, textbox12.TextChanged, _
Handles textbox16.TextChanged
Dim S As Double
If Double.TryParse(Ctype(sender, TextBox).Text, S) Then
' or place the Check code here for all the TextBoxes listed above
checkforonetoten(S)
End If
End Sub
The plain numeric kind:
Private Sub textboxQ_TextChanged(sender As Object, e As EventArgs) _
Handles textbox2.TextChanged, textbox6.TextChanged
Dim S As Double
If Double.TryParse(Ctype(sender, TextBox).Text, S) = False Then
MessageBox.Show("Please enter a number", "Error")
End If
End Sub
Rather than calling a function and passing the current TextBox from events (which is fine), have 2 or 3 events process them all. The point is adding/moving the Handles clause to a common event procedure (be sure to delete the old ones).
If you do decide to call a common function, dont do anything in the events (you still have one per TB) and do it all in the common proc:
Private Sub textboxS_TextChanged(sender As Object, e As EventArgs) _
Handles textboxS.TextChanged
checkforonetoten(Sender)
End Sub
private Sub checkforonetoten(tb As Textbox)
Dim S As Double
If Double.TryParse(tb.Text, S) Then
' your check for 1 - 10 on var S
else
' error: not a valid number
End If
end sub
Also:
If (onetoten > 1 & onetoten < 10) Then
should be:
If (onetoten > 1) AndAlso (onetoten < 10) Then