Public Class Form1
Dim intTicketChoice As Integer
Dim finalCost As Decimal
Dim cost As Decimal
Dim seatType As Integer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Threading.Thread.Sleep(5000)
End Sub
Private Sub cboTypeOfTicket_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTypeOfTicket.SelectedIndexChanged
intTicketChoice = Me.cboTypeOfTicket.SelectedIndex
Me.ListBox1.Items.Clear()
EnableObjects()
Select Case intTicketChoice
Case 0
SingleGame(seatType)
Case 1
Season(seatType)
End Select
End Sub
Sub EnableObjects()
lblNumTickets.Visible = True
txtNumOfTickets.Visible = True
lblSeatType.Visible = True
ListBox1.Visible = True
lblAnswerText.Visible = False
lblCost.Visible = False
btnClear.Visible = True
btnCompute.Visible = True
End Sub
Private Sub SingleGame(ByVal seatType As Integer)
Me.ListBox1.Items.Add("Box Seats $55")
Me.ListBox1.Items.Add("Lower Deck Seats $35")
Me.ListBox1.Items.Add("Upper Deck Seats $25")
Me.ListBox1.Items.Add("Standing Room Only $15")
If ListBox1.SelectedItem = "Box Seats $55" Then
seatType = 0
ElseIf ListBox1.SelectedItem = "Lower Deck Seats $35" Then
seatType = 1
ElseIf ListBox1.SelectedItem = "Upper Deck Seats $25" Then
seatType = 2
ElseIf ListBox1.SelectedItem = "Standing Room Only $15" Then
seatType = 3
End If
End Sub
Private Sub Season(ByVal seatType As Integer)
Me.ListBox1.Items.Add("Box Seats $2500")
Me.ListBox1.Items.Add("Lower Deck Seats $1500")
If ListBox1.SelectedItem = "Box Seats $2500" Then
seatType = 4
Elseif ListBox1.SelectedItem = "Lower Deck Seats $1500" Then
seatType = 5
End If
End Sub
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
Dim ticketNum As Integer
ticketNum = Convert.ToInt32(txtNumOfTickets.Text)
intTicketChoice = cboTypeOfTicket.SelectedIndex
Dim totalCost As Decimal = GetGameCost(ticketNum)
Try
ticketNum = Convert.ToInt32(txtNumOfTickets.Text)
Catch Exception As FormatException
MsgBox("Number of tickets must be numeric")
Return
End Try
'Display cost:
lblAnswerText.Visible = True
Me.lblCost.Text = totalCost.ToString("C")
lblCost.Visible = True
End Sub
Private Function GetGameCost(ByVal ticketNum As Integer)
If seatType = 0 Then
finalCost = (ticketNum * 55D)
ElseIf seatType = 1 Then
finalCost = (ticketNum * 35D)
ElseIf seatType = 2 Then
finalCost = (ticketNum * 25D)
ElseIf seatType = 3 Then
finalCost = (ticketNum * 15D)
ElseIf seatType = 4 Then
finalCost = (ticketNum * 2500D)
ElseIf seatType = 5 Then
finalCost = (ticketNum * 1500D)
End If
Return finalCost
End Function
End Class
Hi guys, I'm stuck on my VB homework. I'm new at this so don't rip me to shreds, hehe. Anyways, Every time I try to compute, it seems to give me 55 * ticketnum instead of look for the actual seatType and use that one. I saw another question on here about this same problem, but couldn't find an answer to my exact question.
Any ideas or tips?
We're not going to rip you to shreds, it's actually a joy to get a homework question where the poster has actually done something rather than dump the assignment question here verbatim, expecting to be spoon-fed :-)
In this case, I'd be looking at the fact that you pass seatType to both SingleGame and Season by value.
That means any changes are only going to be made to the local copy, not the object variable. The object variable will remain at its initial value of zero so that, when you come to calculate the price, it always does the multiply by 55.
Either pass by reference so that changes are reflected back to the object variable, or just use the object variable itself (by not passing it as a parameter at all).
Related
I'm trying to make a Pong knockoff in VB.net. However, I am having difficulty managing to get the ball object to change directions once it gets outside of the screen. This is what I have right now:
Option Explicit On
Option Infer Off
Option Strict On
Public Class Form1
'Declare variables here
Dim P1Score As Integer = 0
Dim P2Score As Integer = 0
Dim velocity As Integer = 1
Dim RandGen As New Random
Dim angle As Integer
'This function defines the X-value movement
Private Function angleCalcX(ByVal angle As Integer) As Integer
Dim xSpeed As Integer
xSpeed = Convert.ToInt16(ball.Location.X + (velocity * System.Math.Cos(angle)))
If ball.Bounds.IntersectsWith(Player1.Bounds) OrElse ball.Bounds.IntersectsWith(Player2.Bounds) Then
xSpeed = Convert.ToInt16(-(ball.Location.X + (velocity * System.Math.Cos(angle))))
End If
Return xSpeed
End Function
Private Function angleCalcY(ByRef angle As Integer) As Integer
Dim ySpeed As Integer
ySpeed = Convert.ToInt16(ball.Location.Y + (velocity * System.Math.Sin(angle)))
If (ball.Bounds.IntersectsWith(background.Bounds)) = False Then
ySpeed = Convert.ToInt16(-(ball.Location.Y + (velocity * System.Math.Sin(angle))))
End If
Return ySpeed
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MessageBox.Show("Hello, and welcome to Pong! This is a 2-player game. Player 1 uses the W and S keys, and Player 2 uses the K and I keys. First to five goals wins. Press space to start!", "Start Screen.jpg", MessageBoxButtons.OK, MessageBoxIcon.Information)
angle = RandGen.Next(1, 360)
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
ball.Location = New Point(angleCalcX(angle), angleCalcY(angle))
If ball.Location.X > 1049 Then
P1Score += 1
velocity = 1
ElseIf ball.Location.X < 12 Then
P2Score += 1
velocity = 1
End If
End Sub
Public Sub Form1_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
If e.KeyCode = Keys.S Then
Player1.Top += 25
ElseIf e.KeyCode = Keys.W Then
Player1.Top -= 25
ElseIf e.KeyCode = Keys.K Then
Player2.Top += 25
ElseIf e.KeyCode = Keys.I Then
Player2.Top -= 25
End If
End Sub
Private Sub quitButton_Click(sender As Object, e As EventArgs) Handles quitButton.Click
Me.Close()
End Sub
End Class
Can anyone help me out?
There's missing something like this in your Timer2_Tick
ElseIf ball.Location.Y < 12 OrElse ball.Location.Y > 600 Then
ySpeed = -ySpeed 'Make a bounce from top/bottom edge
But there's a lot to improve in the rest of code as well. I don't see the reason to use Int16 for speeds or hard-coding boundaries in code for example.
I'm making a program that allows users to see information on songs, play an excerpt of them, and purchase selected ones.
And allow users to click the Purchase button to buy the indicated tune.
When checking out:
Users cannot checkout if they have not purchased any tunes, however they can exit the program.
Use an InputBox so that users can enter their sales tax rate. Since users are entering a value, you must perform data validation on their input.
Allow users to cancel the check out process by clicking the InputBox Cancel button.
When the input box is displayed, the textbox should have the focus, and when an incorrect tax value is added, the incorrect value should be cleared and the textbox should have focus again.
Use Write/Writeline to create a purchase order text file named PurchaseOrder.txt that includes the date the file was created and an itemized list of purchases, the subtotal, tax, and total.
When I click on the "Purchase" button of the selected song and click on the "Check Out" button, I get an error that say: "You have not ordered any items". Please refer to the cmdCheckOut_Click subroutine in the code below. I think that's where I'm getting my errors.
Here's the code:
Public Structure musicInfo
<VBFixedString(30)> Public title As String
<VBFixedString(20)> Public artist As String
<VBFixedString(20)> Public genre As String
<VBFixedString(10)> Public duration As String
Public year As Integer
Public price As Double
<VBFixedString(15)> Public songFileName As String
End Structure
Public Const NoOfTunes = 5
Public songs(NoOfTunes - 1) As musicInfo
Option Explicit On
Imports System.IO
Public Class frmTunes
Public index As Integer
Public purchaseCount As Integer
Public purchasePrice(10) As Decimal
Public purchaseTitle(10) As String
Private Sub frmTunes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
FileOpen(1, "music.dat", OpenMode.Random, , , Len(songs(0)))
For i = 0 To NoOfTunes - 1
FileGet(1, songs(i))
Next
FileClose(1)
cmdPrevious.Visible = False
DisplaySong(0)
End Sub
Sub DisplaySong(ByVal i As Int32)
lblTitle.Text = songs(i).title
lblArtist.Text = songs(i).artist
lblGenre.Text = songs(i).genre
lblDuration.Text = songs(i).duration
lblYear.Text = Convert.ToString(songs(i).year)
lblPrice.Text = Convert.ToString(songs(i).price)
End Sub
Private Sub cmdStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdStop.Click
My.Computer.Audio.Stop()
End Sub
Private Sub cmdPurchase_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPurchase.Click
purchaseTitle(purchaseCount) = lblTitle.Text
purchasePrice(purchaseCount) = Convert.ToDecimal(lblPrice.Text)
purchaseCount = (purchaseCount + 1)
End Sub
Private Sub cmdPrevious_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPrevious.Click
index = (index - 1)
If (index < 4) Then
cmdNext.Visible = True
End If
If (index = 0) Then
cmdPrevious.Visible = False
End If
DisplaySong(index)
End Sub
Private Sub cmdNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNext.Click
index = (index + 1)
If (index = NoOfTunes - 1) Then
cmdNext.Visible = False
End If
If (index > 0) Then
cmdPrevious.Visible = True
End If
DisplaySong(index)
End Sub
Private Sub cmdPlay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdPlay.Click
My.Computer.Audio.Play(songs(index).songFileName)
End Sub
Private Sub cmdCheckOut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCheckOut.Click
Dim decimal1 As Decimal
Dim decimal3 As Decimal
Dim decimal4 As Decimal
Dim str1 As String = ""
If (Not purchaseCount) Then
MsgBox("You have not ordered any items!", MsgBoxStyle.Exclamation, "Order Error")
Else
Do While ((IsNumeric(str1) Or (Decimal.Compare(decimal3, Decimal.Zero) < 0)) Or (Decimal.Compare(decimal3, (10D)) > 0))
str1 = InputBox("Enter your tax rate as a % between and including 0 - 10:", "Tax Rate", "", -1, -1)
If (str1 <> "") Then
If (Not IsNumeric(str1)) Then
MsgBox("You must enter a numeric tax rate", MsgBoxStyle.Exclamation, "Tax Rate Error")
Else
Dim dec3 As Decimal = Convert.ToDecimal(str1)
If ((Decimal.Compare(decimal3, Decimal.Zero) < 0) Or (Decimal.Compare(decimal3, (10D)) > 0)) Then
MsgBox("You must enter a tax rate between and including 0% - 10%", MsgBoxStyle.Exclamation, "Tax Rate Error")
End If
End If
End If
Loop
Dim StreamWriter As StreamWriter = File.CreateText("PurchaseOrder.txt")
StreamWriter.WriteLine("For Purchases dated: " & DateTime.Now.ToLongDateString())
StreamWriter.WriteLine()
Dim num2 As Integer = (purchaseCount - 1)
Dim num1 As Integer = 0
Do While (num1 <= num2)
StreamWriter.Write(Strings.FormatCurrency(CType(Me.purchasePrice(num1), Decimal) & " "))
StreamWriter.WriteLine(Me.purchaseTitle(num1))
Dim dec1 As Decimal = Decimal.Add(Nothing, Me.purchasePrice(num1))
num1 = (num1 + 1)
Loop
StreamWriter.WriteLine("------")
StreamWriter.WriteLine(Strings.FormatCurrency(CType(decimal1, Decimal) & " Subtotal"))
Dim decimal2 As Decimal = New Decimal(((Convert.ToDouble(decimal3) * 0.01) * Convert.ToDouble(decimal1)))
StreamWriter.WriteLine(Strings.FormatCurrency(CType(decimal2, Decimal) & " Tax"))
StreamWriter.WriteLine("------")
Dim dec4 As Decimal = Decimal.Add(decimal1, decimal2)
StreamWriter.WriteLine(Strings.FormatCurrency(CType(decimal4, Decimal) & " Total"))
MsgBox("Purchase Order has been created", MsgBoxStyle.OkOnly)
StreamWriter.Close()
Me.Close()
End If
End Sub
End Class
Not doesn't do what you think it does. In VB.Net the Not operator performs a bitwise invert on non-boolean value. So if purchaseCount = 1 then Not purchaseCount = 0xFFFFFFFE = -2, which with convert to True. Only an integer value of 0, whould convert to false.
Change the test If (Not purchaseCount) to If (purchaseCount = 0)
My code needs a little work
Public Class Form1
Dim Bread, TotalPrice As Double
Private Sub txtBread_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBread.TextChanged
If txtBread.Text = "" Then
TotalPrice = TotalPrice - Bread
lblBread.Text = Bread.ToString
lblPrice.Text = TotalPrice.ToString
Else
Bread = Val(txtBread.Text) * 3.25
lblBread.Text = Bread.ToString
TotalPrice = TotalPrice + Bread
lblPrice.Text = TotalPrice.ToString
End If
End Sub
End Class
My textbox is good for a one-digit number only.
So my error here is when i input two-digit numbers on my text box, it actually updates my labels, but when i press backspace it does not update anymore.
The value of the variable TotalPrice grows with each new input (no matter if it is bigger or smaller than the previous one) and thus the value of lblPrice.Text. For example:
txtBread.Text TotalPrice
1 1
15 16
1 17
If you explain what you want to accomplish exactly, I can update your code.
Dim Bread As Double
Dim TotalPrice as Double = 5 'Any constant value you want
Private Sub txtBread_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBread.TextChanged
If txtBread.Text = "" Then
lblBread.Text = Bread.ToString
lblPrice.Text = Convert.ToString(TotalPrice - Bread)
Else
Bread = Val(txtBread.Text) * 3.25
lblBread.Text = Bread.ToString
lblPrice.Text = Convert.ToString(TotalPrice + Bread)
End If
End Sub
Try with my sample ..
Public Class Form1
Dim Bread As Double
Dim TotalPrice As Double = 100 '---> maybe this is a result from a function
Private Sub txtBread_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtBread.TextChanged
If txtBread.Text = "" Then
Bread = 0
Else
Bread = Val(txtBread.Text) * 3.25
End If
lblBread.Text = Bread.ToString
lblPrice.Text = (TotalPrice + Bread).ToString
End Sub
End Class
Public Class MainForm
Private Sub exitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub guestsTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles guestsTextBox.KeyPress
' allows only numbers and the Backspace key
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'fills the list box and selects the first item
typeListBox.Items.Add("Kid's Birthday")
typeListBox.Items.Add("21st Birthday")
typeListBox.Items.Add("40th Birthday")
typeListBox.Items.Add("Other Birthday")
typeListBox.SelectedIndex = 0
End Sub
Private Sub calcButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles calcButton.Click
'displays the total charge
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Integer.TryParse(guestsTextBox.Text, guests)
typeIndex = typeListBox.SelectedIndex
'determine the price per guest
Select Case typeIndex
Case 0 'Kid's Birthday
guestPrice = 11
Case 1 '21st Birthday
guestPrice = 20
Case 2 '40th Birthday
guestPrice = 25
Case Else 'other birthdays
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
totalLabel.Text = totalCharge.ToString("C0")
End Sub
Private Sub testDataButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles testDataButton.Click
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Dim randomGen As New Random
Dim setCounter As Integer = 1
testDataLabel.Text = String.Empty
Do
guests = randomGen.Next(1, 51)
typeIndex = randomGen.Next(0, 4)
For Each I As Object In typeListBox.SelectedItems
testDataLabel.Text += I.ToString() & ControlChars.NewLine
Next
'determine the price per guest
Select Case typeListBox.SelectedIndex
Case 0
guestPrice = 11
Case 1
guestPrice = 20
Case 2
guestPrice = 25
Case Else
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
testDataLabel.Text = testDataLabel.Text &
typeIndex.ToString & " " &
guests.ToString & " " &
totalCharge.ToString("C0") &
ControlChars.NewLine
setCounter += 1
Loop Until setCounter > 10
End Sub
Private Sub typeListBox_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles typeListBox.SelectedIndexChanged
End Sub
End Class
When I click on a button named "Generate Test Data" It generates a list of random numbers in a label. I want these numbers to say the type of birthday instead of the number.
0 being "Kid's Birthday"
1 being "21st Birthday"
2 being "40th Birthday"
and 3 being "Other Birthday"
How would I go about doing this?
Any help would be much appreciated!
If I understood your question correctly, you can declare an enum and have a dictionary of that enum to String.
The Enum takes care of dealing with numbers in code, and rather use human readable constructs. Dictionary will make sure your users will also see human readable constructs.
Please see below code (needs a brand new WinForms project and a ListBox called ListBox1 on the main form):
Option Strict On
Public Class Form1
'Declare this enum to avoid dealing with naked numbers in code
Enum BirthdayTypes
btKids = 0
bt21st = 1
bt40th = 2
btOther = 3
End Enum
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) _
Handles MyBase.Load
'Suppose your input value is a number,
'but you don't want to deal with numbers
Dim typeIndex As Integer = 2
'You can convert your number to BirthdayTypes,
'making your input "correct"
Dim typeIndexBt As BirthdayTypes = ConvertBirthdayIndexToType(typeIndex)
'Calculation of guest price is now "human readable"
Dim guestPrice As Integer = CalculateGuestPrice(typeIndexBt)
'You can create a dictionary for diplaying the values
Dim displayDictionary As New Dictionary(Of BirthdayTypes, String)
With displayDictionary
.Add(BirthdayTypes.btKids, "Kid's Birthday")
.Add(BirthdayTypes.bt21st, "21st Birthday")
.Add(BirthdayTypes.bt40th, "40th Birthday")
.Add(BirthdayTypes.btOther, "Other Birthday")
End With
'Here is how you would those values into a ListBox
With ListBox1
.DataSource = displayDictionary.ToList
.ValueMember = "Key"
.DisplayMember = "Value"
End With
'Now your ListBox displays strings,
'but SelectedValue would return an object of type BirthdayTypes
'You can extract random values from the above dictionary by index,
'and create a new list from it
Debug.WriteLine(ListBox1.SelectedValue) 'outputs btKids
End Sub
Private Function CalculateGuestPrice(bt As BirthdayTypes) As Integer
Select Case bt
Case BirthdayTypes.btKids : Return 11
Case BirthdayTypes.bt21st : Return 20
Case BirthdayTypes.bt40th : Return 25
Case BirthdayTypes.btOther : Return 15
End Select
'should never here
Throw New Exception("Unknown birthday type")
End Function
Private Function ConvertBirthdayIndexToType(index As Integer) As BirthdayTypes
If index < 3 Then Return CType(index, BirthdayTypes)
Return BirthdayTypes.btOther
End Function
End Class
Disclaimer: this code is just a demo of what can be done, not meant to be used a complete solution.
I would use a string.
Dim thestring() As String = {"Kid's Birthday", _
"21st Birthday", _
"40th Birthday", _
"Other Birthday"}
Now each of those numbers will represent the text in thestring.
thestring(0) = kids birthday
thestring(1) = 21 birthday
thestring(2) = 40th birthday
thestring(3) = other birthday
Make sense? I would help further, but i don't quite get what you are trying to do.
I'm working on a visual basic application( w/ visual studio 2010) that calculates ticket sales. This one is been really challenging since i'm a newbie when it comes to visual basic.
I'm i'm having trouble getting the calculate button to
Here are the instruction to get the costs from the functions and use them to calculate the total. Here are the instructions they give me.
User selects whether to purchase season tickets or single-game tickets
User enters the number of tickets needed and the type of seats based on whether they selected season single-game tickets.
User clicks the Compute Ticket Cost Button to display final cost
User clicks the Clear Form button to clear the response
I'm stuck on the calculating button. I just need to be able to capture the cost from the button and then use the button to compute it.
Public Class Form1
'Global Variables
Dim intTicketChoice As Integer
Dim finalCost As Decimal
Dim cost As Decimal
Private Sub cboTicketType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTicketType.SelectedIndexChanged
intTicketChoice = Me.cboTicketType.SelectedIndex
Me.lstSeatType.Items.Clear()
Select Case intTicketChoice
Case 0 : SingleGame()
Case 1 : Seasonal()
End Select
'Make Items visible
Me.lblCostDisplay.Visible = True
Me.lblSeats.Visible = True
Me.lblTickets.Visible = True
Me.lstSeatType.Visible = True
Me.txtTicketNum.Visible = True
Me.btnClear.Visible = True
Me.btnCompute.Visible = True
Me.txtTicketNum.Focus()
End Sub
Private Sub SingleGame()
Dim seatType As Integer
'Add List Items
Me.lstSeatType.Items.Add("Box Seats $55")
Me.lstSeatType.Items.Add("Lower Deck Seats $35")
Me.lstSeatType.Items.Add("Upper Deck Seats $25")
Me.lstSeatType.Items.Add("Standing Room Only $15")
If lstSeatType.SelectedItem = "Box Seats $55" Then
seatType = 0
End If
If lstSeatType.SelectedItem = "Lower Deck Seats $35" Then
seatType = 1
End If
If lstSeatType.SelectedItem = "Upper Deck Seats $25" Then
seatType = 2
End If
If lstSeatType.SelectedItem = "Standing Room Only $15" Then
seatType = 3
End If
End Sub
Private Sub Seasonal()
Dim seatType As Integer
'Add List Items
Me.lstSeatType.Items.Add("Box Seats $2500")
Me.lstSeatType.Items.Add("Lower Deck Seats $1500")
'Price Items for Single Games
If lstSeatType.SelectedItem = "Box Seats $2500" Then
seatType = 4
End If
If lstSeatType.SelectedItem = "Lower Deck Seats $1500" Then
seatType = 5
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
Dim ticketNum As Integer
Dim totalCost As Decimal
ticketNum = Convert.ToInt32(Me.txtTicketNum.Text)
intTicketChoice = Me.cboTicketType.SelectedIndex
Select Case intTicketChoice
Case 0 : totalCost = SingleGameCost()
Case 1 : totalCost = SeasonalCost()
End Select
'try and catch number textbox
Try
ticketNum = Convert.ToInt32(txtTicketNum.Text)
Catch Exception As FormatException
MsgBox("Number of tickets must be numeric")
Return
End Try
'display cost of tickets
Me.lblCostDisplay.Text = "The total cost of tickets purchased:" & totalCost.ToString("C")
End Sub
Private Function SingleGameCost(ByVal seatType As Integer, ByVal ticketNum As Integer)
finalCost = ticketNum * cost
'Price Items for Single Games
If seatType = 0 Then
cost = 55D
End If
If seatType = 1 Then
cost = 35D
End If
If seatType = 2 Then
cost = 25D
End If
If seatType = 3 Then
cost = 15D
End If
Return finalCost
End Function
Private Function SeasonalCost(ByVal seatType As Integer, ByVal ticketNum As Integer, ByRef cost As Decimal)
Dim finalCost As Decimal
If seatType = 4 Then
cost = 2500D
End If
If seatType = 0 Then
cost = 1500D
End If
finalCost = cost * ticketNum
Return finalCost
End Function
End Class
the error is happening here :
If intTicketChoice = 0 Then
SingleGameCost()
End If
If intTicketChoice = 1 Then
SeasonalCost()
End If
with the singlegamecost() function and the seasonacost() function.
You need to have the seatType as a Public Variable.
then once they select the Seat you set that Variable
and then use the variable when you are Computing.
Then return the Cost.
In the Compute Function
After you have got the final cost then
me.lblCostDisplay.Text = finalCost.ToString()
I have modified this a little for you. Take what you want from it.
I have not tested it. Hope this helps... Not sure why the formating
did not come out quite right..
Public Class Form1
Private SeatType As Integer = 0
Private Sub cboTicketType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboTicketType.SelectedIndexChanged
Dim intTicketChoice As Integer = Me.cboTicketType.SelectedIndex
Me.lstSeatType.Items.Clear()
Select Case intTicketChoice
Case 0
Me.lstSeatType.Items.Add("Box Seats $55")
Me.lstSeatType.Items.Add("Lower Deck Seats $35")
Me.lstSeatType.Items.Add("Upper Deck Seats $25")
Me.lstSeatType.Items.Add("Standing Room Only $15")
Case 1
Me.lstSeatType.Items.Add("Box Seats $2500")
Me.lstSeatType.Items.Add("Lower Deck Seats $1500")
Case Else
End Select
'Make Items visible
Me.lblCostDisplay.Visible = True
Me.lblSeats.Visible = True
Me.lblTickets.Visible = True
Me.lstSeatType.Visible = True
Me.txtTicketNum.Visible = True
Me.btnClear.Visible = True
Me.btnCompute.Visible = True
Me.txtTicketNum.Focus()
End Sub
Private Sub lstSeatType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lstSeatType.SelectedIndexChanged
If lstSeatType.SelectedItem.ToString.ToLower = "box seats $55" Then
SeatType = 0
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "lower deck seats $35" Then
SeatType = 1
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "upper deck seats $25" Then
SeatType = 2
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "standing room only $15" Then
SeatType = 3
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "box seats $2500" Then
SeatType = 4
ElseIf lstSeatType.SelectedItem.ToString.ToLower = "lower deck seats $1500" Then
SeatType = 5
End If
End Sub
Private Sub btnCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCompute.Click
Dim sTicketNum As String = txtTicketNum.Text
If Not String.IsNullOrEmpty(sTicketNum) Then
Try
Dim ticketNum As Integer = Convert.ToInt32(Me.txtTicketNum.Text)
Dim totalCost As Decimal = GetGameCost(ticketNum)
'try and catch number textbox
Me.lblCostDisplay.Text = "The total cost of tickets purchased: " & totalCost.ToString("C")
Catch Exception As FormatException
MsgBox("Number of tickets must be numeric")
Return
End Try
'display cost of tickets
Else
MsgBox("Please input a ticket number.")
txtTicketNum.focus()
Return
End If
End Sub
Private Function GetGameCost(ByVal ticketNum As Integer) As Decimal
Dim finalCost As Decimal = 0
'Price Items for Single Games
Select Case SeatType
Case 0
finalCost = (ticketNum * 55D)
Case 1
finalCost = (ticketNum * 35D)
Case 2
finalCost = (ticketNum * 25D)
Case 3
finalCost = (ticketNum * 15D)
Case 4
finalCost = (ticketNum * 1500D)
Case 5
finalCost = (ticketNum * 2500D)
Case Else
End Select
'
Return finalCost
'
End Function
End Class
There are numerous issues with the above code. It needs heavy refactoring. But even without that, the question cannot be fully answered in the current form for the following reason - You are calling SingleGameCost and SeasonalCost without parameters, however they are declared with such.
This code would not compile. If it does compile at your side, there is some code you did include to support the question. If it does not compile, this is the answer.
Regarding refactoring, clauses like this:
If lstSeatType.SelectedItem = "Box Seats $55" Then
seatType = 0
End If
If lstSeatType.SelectedItem = "Lower Deck Seats $35" Then
seatType = 1
End If
If lstSeatType.SelectedItem = "Upper Deck Seats $25" Then
seatType = 2
End If
If lstSeatType.SelectedItem = "Standing Room Only $15" Then
seatType = 3
End If
Can be rewritten:
Select Case lstSeatType.SelectedItem
Case "Box Seats $55" : seatType = 0
Case "Lower Deck Seats $35" : seatType = 1
Case "Upper Deck Seats $25" : seatType = 2
Case "Standing Room Only $15" : seatType = 3
End Select
Even though, as written, value of seatType would be lost, because it is declared as a local variable.
Strange. I'm getting no errors when I wrote the code, though I still have to write the Clear Code for it - but I'll go ahead and give the code I have at the moment.
Public Class BaseballTickets
Private _strBoxSeats As String = "Box Seats"
Private _strLowerDeck As String = "Lower Deck"
Private _strUpperDeck As String = "Upper Deck"
Private _strStandingRoomOnly As String = "Standing Room Only"
Private Sub lblBaseballTicketSales_Click(sender As System.Object, e As System.EventArgs) Handles lblBaseballTicketSales.Click
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub cboxTicketType_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cboxTicketType.SelectedIndexChanged
Dim intTicketType As Integer
intTicketType = Me.cboxTicketType.SelectedIndex
lstSeatingType.Items.Clear()
Select Case intTicketType
Case 0
SeasonTickets()
Case 1
SingleGameTickets()
End Select
lblBaseballTicketSales.Visible = True
lblNumberOfGroup.Visible = True
lblTicketChoice.Visible = True
lblTicketCost.Visible = True
lblTicketCost.Text = ""
txtAmountOfPeople.Focus()
End Sub
Private Sub SeasonTickets()
lstSeatingType.Items.Add(_strBoxSeats)
lstSeatingType.Items.Add(_strLowerDeck)
End Sub
Private Sub SingleGameTickets()
lstSeatingType.Items.Add(_strBoxSeats)
lstSeatingType.Items.Add(_strLowerDeck)
lstSeatingType.Items.Add(_strStandingRoomOnly)
lstSeatingType.Items.Add(_strUpperDeck)
End Sub
Private Sub btnCost_Click(sender As System.Object, e As System.EventArgs) Handles btnCost.Click
Dim intGroupSize As Integer
Dim blnNumberInPartyIsValid As Boolean = False
Dim blnTicketIsSelected = False
Dim intTicketType As Integer
Dim strSelectedTicket As String = ""
Dim intTicketChoice As Integer
Dim decTotalCost As Decimal
blnNumberInPartyIsValid = ValidateNumberInParty()
intTicketChoice = ValidateTicketIsSelected(blnTicketIsSelected, strSelectedTicket)
If (blnNumberInPartyIsValid And blnTicketIsSelected) Then
intGroupSize = Convert.ToInt32(txtAmountOfPeople.Text)
intTicketType = Me.cboxTicketType.SelectedIndex
Select Case intTicketType
Case 0
decTotalCost = SeasonTicketsFindCost(intTicketType, _
intGroupSize)
Case 1
decTotalCost = SingleGameTicketsFindCost(intTicketType, _
intGroupSize)
End Select
lblTicketCost.Text = "The total cost of tickets purchased: " & decTotalCost.ToString("C")
End If
End Sub
Private Function ValidateNumberInParty() As Boolean
Dim intNumberOfPeople As Integer
Dim blnValidityCheck As Boolean = False
Dim strNumberInPartyErrorMessage As String = _
"Please Enter the Number of people Accompanying you (1-99)"
Dim strMessageErrorTitle As String = "Error"
Try
intNumberOfPeople = Convert.ToInt32(txtAmountOfPeople.Text)
If intNumberOfPeople > 0 And intNumberOfPeople < 100 Then
blnValidityCheck = True
Else
MsgBox(strNumberInPartyErrorMessage, , strMessageErrorTitle)
txtAmountOfPeople.Focus()
txtAmountOfPeople.Clear()
End If
Catch Exception As FormatException
MsgBox(strNumberInPartyErrorMessage, , strMessageErrorTitle)
txtAmountOfPeople.Focus()
txtAmountOfPeople.Clear()
Catch Exception As OverflowException
MsgBox(strNumberInPartyErrorMessage, , strMessageErrorTitle)
txtAmountOfPeople.Focus()
txtAmountOfPeople.Clear()
Catch Exception As SystemException
MsgBox(strNumberInPartyErrorMessage, , strMessageErrorTitle)
txtAmountOfPeople.Focus()
txtAmountOfPeople.Clear()
End Try
Return blnValidityCheck
End Function
Private Function ValidateTicketIsSelected(ByRef blnTicket As Boolean, _
ByRef strTicket As String) As Integer
Dim intTicketChoice As Integer
Try
intTicketChoice = Convert.ToInt32(lstSeatingType.SelectedIndex)
strTicket = lstSeatingType.SelectedItem.ToString()
blnTicket = True
Catch Exception As SystemException
' Detects if a tour not selected
MsgBox("Select a Ticket Choice", , "Error")
blnTicket = False
End Try
Return intTicketChoice
End Function
Private Function SeasonTicketsFindCost(ByVal intTicketSelection As Integer, _
ByVal intGroupSize As Integer) As Decimal
Dim decTicketCost As Decimal
Dim decFinalCost As Decimal
Dim decBoxSeats As Decimal = 2500D
Dim decLowerdeck As Decimal = 1500D
Select Case intTicketSelection
Case 0
decTicketCost = decBoxSeats
Case 1
decTicketCost = decLowerdeck
End Select
decFinalCost = decTicketCost * intGroupSize
Return decFinalCost
End Function
Private Function SingleGameTicketsFindCost(ByVal intTicketSelection As Integer, _
ByVal intGroupSize As Integer) As Decimal
Dim decTicketCost As Decimal
Dim decFinalCost As Decimal
Dim decBoxSeats As Decimal = 55D
Dim decLowerDeck As Decimal = 35D
Dim decUpperDeck As Decimal = 25D
Dim decStandingRoomOnly As Decimal = 15D
Select Case intTicketSelection
Case 0
decTicketCost = decBoxSeats
Case 1
decTicketCost = decLowerDeck
Case 2
decTicketCost = decUpperDeck
Case 3
decTicketCost = decStandingRoomOnly
End Select
decFinalCost = decTicketCost * intGroupSize
Return decFinalCost
End Function
End Class