Calculating from properties of different objects OOP VB - vb.net

I am practicing OOP using VB. I creating a simple kiosk like program for a sandwich shop which the user will be able to select different items from i.e sandwiches, drinks, sides.
I have created a class for the sandwiches:
Public Class sandwich
Public Sub sandwich(sandwichName As String, sandwichDescription As String, sandwichCost As Decimal)
Me.sandwichName = sandwichName
Me.sandwichDescription = sandwichDescription
Me.sandwichDescription = sandwichCost
'me. refers to the current instance of the class
End Sub
And the objects for these sandwiches with the event handler
Private Sub btnChickpeaPlus_Click(sender As Object, e As EventArgs) Handles btnChickpeaPlus.Click
Dim garlicButterChkpea As New sandwich
garlicButterChkpea.sandwichName = "Garlic Butter Chickpea"
garlicButterChkpea.sandwichCost = 7.99
garlicButterChkpea.sandwichDescription = "Mashed chickpeas on wheat bread with sliced tomato, red onion, lettuce and garlic sauce"
ListBox1.Items.Add(1 & " " & garlicButterChkpea.sandwichName & " " & garlicButterChkpea.sandwichCost)
'the name and cost of the sandwich will be displayed in a listbox when item is selected
txtChickpea.Text += 1
'adds item by one whenever the plus sign is clicked
End Sub
Private Sub btnAvocadoPlus_Click(sender As Object, e As EventArgs) Handles btnAvocadoPlus.Click
Dim avocadoReuben As New sandwich
avocadoReuben.sandwichName = "Avocado Reuben"
avocadoReuben.sandwichDescription = "Avocado with saukeraut, sliced tomatoes on Rye bread with vegan mayo"
avocadoReuben.sandwichCost = 7.99
ListBox1.Items.Add(1 & " " & avocadoReuben.sandwichName & " " & avocadoReuben.sandwichCost)
'the name and cost of the sandwich will be displayed in a listbox when item is selected
txtAvocado.Text += 1
'adds item by one whenever the plus sign is clicked
End Sub
Private Sub btnTunaPlus_Click(sender As Object, e As EventArgs) Handles btnTunaPlus.Click
Dim tunaMayo As New sandwich
tunaMayo.sandwichName = "Tuna Mayo"
tunaMayo.sandwichDescription = "Wild Tuna in olive oil with vegan mayo with organic
lettuce and diced red onion"
tunaMayo.sandwichCost = 8.99
ListBox1.Items.Add("1" & " " & tunaMayo.sandwichName & " " & tunaMayo.sandwichCost)
'the name and cost of the sandwich will be displayed in a listbox when item is selected
txtTuna.Text += 1
'adds item by one whenever the plus sign is clicked
End Sub
I am currently calculating the total price of selected objects using this code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
tunaCost = 8.99 * Val(txtTuna.Text)
steakCost = 9.99 * Val(txtSteak.Text)
chickpeaCost = 7.99 * Val(txtChickpea.Text)
avocadoCost = 7.99 * Val(txtAvocado.Text)
lemonadeCost = 4.99 = Val(txtboxLemonade.Text)
cokeCost = 2.99 = Val(txtCoke.Text)
txtBoxTotal.Text = tunaCost + steakCost + avocadoCost + chickpeaCost + lemonadeCost + cokeCost
'when the complete order cost is clicked the total cost of the order will be added
lblTotal.Text = txtBoxTotal.Text
End Sub
I had to declare separate variables such as cokeCost because I couldn't figure out how to calculate the costs from the objects themselves.
I was also having trouble creating a drinks class so I just declared the drinks under the sandwich class properties like so:
Private Sub btnLemonadePlus_Click(sender As Object, e As EventArgs) Handles btnLemonadePlus.Click
Dim lemonade As New sandwich
lemonade.sandwichName = "Lemonade"
lemonade.sandwichCost = 4.99
lemonade.sandwichDescription = "Freshly squeezed lemonade"
ListBox1.Items.Add(1 & " " & lemonade.sandwichName & " " & lemonade.sandwichCost)
txtboxLemonade.Text += 1
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles btnCokePlus.Click
Dim coke As New sandwich
coke.sandwichName = "Coke"
coke.sandwichCost = 2.99
coke.sandwichDescription = "Orignial Coca-Cola in 500ml bottle"
ListBox1.Items.Add(1 & " " & coke.sandwichName & " " & coke.sandwichCost)
txtCoke.Text += 1
End Sub
I think I could probably just change the parent class name to just item and have the drinks and sandwiches inherit off of that.
Can anyone advice me on how to make the code simpler and how to create a function that could calculate the total cost of selected items instead of creating more variables please?

I think I could probably just change the parent class name to just
item and have the drinks and sandwiches inherit off of that.
Yes, you should do that. I suggest to create 2 base classes, one for food and one for drinks. And if you want to go fancy with practicing OOP, consider to define Interfaces that your objects implement.
As for calculating costs, add a method to your object that does this, This one lets you adjust the item cost "on the fly" if needed, e.g. in the evening sell the last sandwiches at a discount to clear your stock:
Public Class sandwich
Public Function GetTotal(ByVal numberOf As Int32, Optional price As Currency = 0) As Currency
' Price differs from normal item price? Could be an item at discount or a premium
If price > 0 Then
Return numberOf * price
Else
Return numberOf * Me.sandwichCost
End If
End Function
End Class

Related

How to add the sum in the listbox(visual basic) mix with other value, the value should get it price number

from combobox to the dish i used if statement to display my dish in my dish area,
from dish to the list i used:
Dim quantity As Integer
quantity = txtQuantity.Text
If lstDish.SelectedIndex > -1 Then
Dim index1 As Integer
index1 = lstDish.SelectedIndex
Dim item1 As Object
item1 = lstDish.SelectedItem
lstList.Items.Add(item1 & " --> " & quantity)
End If
txtQuantity.Text = 1
The value display at list are will be in form Noodle -> 2
What should i do to get the noodle value as 3.50 * my quantity 2 and add all my sum for the list
Dim Total As Integer
Dim priceOfDish As String = 0
Dim quantity As Integer
Dim friesPrice, garlicBreadPrice, friedChickenWingPrice, springRollPrice As Double
Dim chickenRicePrice, friedRicePrice, curryRicePrice, thaiChickenRice As Double
Dim friedSeafoodNoodlePrice, chickenNoodlePrice, beefNoodlePrice, prawnNoodlePrice As Double
Select Case priceOfDish
Case Is = "Fries"
friesPrice += 2.5
Case Is = "Garlic Bread"
garlicBreadPrice += 2.5
Case Is = "Fried Chicken Wing"
friedChickenWingPrice += 2.5
Case Is = "Spring Roll"
springRollPrice += 2.5
Case Is = "Chicken Rice"
chickenRicePrice += 4
Case Is = "Fried Rice"
friedRicePrice += 4
Case Is = "Curry Rice"
curryRicePrice += 4
Case Is = "Thai Chicken Rice"
thaiChickenRice += 4
Case Is = "Fried Seafood Noodle"
friedSeafoodNoodlePrice += 3.5
Case Is = "Chicken Noodle"
chickenNoodlePrice += 3.5
Case Is = "Beef Noodle"
beefNoodlePrice += 3.5
Case Is = "Prawn Noodle"
prawnNoodlePrice += 3.5
End Select
Total = priceOfDish * quantity
txtTotal.Text = Total
End Sub
code for the total button
I have only included the code to demonstrate one method of getting the total. As several others have mentioned, a Class is probably the best method but I don't think you have reached the use of classes in your course yet.
I have declared 2 form level variables to hold values that can be accessed from more than one method. They do not lose their values at the end of a Sub but maintain them as long as the Form is open. You will need to reset the RunningTotal button to 0 in your Clear button.
When the user selects a category the code resets the value of CategoryCost is set so it is ready if the user chooses to add an item form this category. It is reset every time a new category is chosen.
It is then a simple matter to calculate the cost and add it to the RunningTotal in the AddButton. Then it is displayed in the txtTotal by calling .ToString with the "C2" parameter which stands for Currency with 2 numbers after the decimal point.
Private RunningTotal As Decimal
Private CategoryCost As Decimal
Private Sub ComboBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox1.SelectedIndexChanged
Dim Category = ComboBox1.Text
Select Case Category
'Add your code to display the products in each category in the left hand list box
Case "Snack"
CategoryCost = 2.5D
Case "Noodle"
CategoryCost = 3.5D
Case "Rice"
CategoryCost = 4D
Case Else
CategoryCost = 0D
End Select
End Sub
Private Sub AddButton_Click(sender As Object, e As EventArgs) Handles AddButton.Click
'Your code to display the selected item from the left list box in the right list box
'can be entered here.
RunningTotal += CDec(txtQuantity.Text) * CategoryCost
'If you don't want to display a running total, put the following code in a total button
txtTotal.Text = RunningTotal.ToString("C2")
End Sub
You can create a database for store products and a table for products
By this query
Put like this query on button click event
Declare #sum as integer=0
Select #sum=product_cost * “+val(textboxcount.text)+” from product_table where product_name=“+listbox.selelcttext+” <—-listbox selected
Declare a variable in the form and do your calculation in the Add Button (Not Total Button)
Public Class MyForm
dim MyTotal as Double
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
' Do your stuff to move from dishes to the list
MyTotal = MyTotal + (cdbl(txtQuantity.Text) * Price)
End Sub
Private Sub btnTotal_Click(sender As Object, e As EventArgs) Handles btnTotal.Click
txt_Total.text = MyTotal.ToString("N2")
End Sub
End Class

Adding 1 everytime i use button vb.net

Basically, I need 2 make a student number and after every new entry I put the student number should +1 so 20182(or 3 if male)001 will be 20182(or 3 if male)002 after I push the button and it must keep +1 but once it reaches the 10th registered student the format changes to 20182(3 if male)010.
I have done everything but make the number +1 every time I use the button
so basically the answer must be:
Student Number is 20182001
Surname , Name
contact details
but, I done everything besides the 001, 002,003 till 010 part so if anybody could help I would be thankful
Public Class Form1
Public Number As Integer = 2018000
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strSurname As String
Dim strFullName As String
Dim strContact As String
Dim strGender As String
Dim x As Integer
'IF statement'
If Me.cboGender.SelectedItem = "Female" Then
Number = 2018300
Else
End If
If Me.cboGender.SelectedItem = "Male" Then
Number = 2018200
Else
End If
'Finding The Student Number'
Dim i As Integer = 0
Do While (i < 1)
i = i + 1
Loop
If i = 201820010 Then
Number = 201800
Else
If i = 201830010 Then
Number = 201800
End if
End If
'Add Items To ListBox'
ListBox1.Items.Add("Student number: " & Number & i)
ListBox1.Items.Add(txtSurname.Text & " , " & txtFullName.Text)
ListBox1.Items.Add(txtContact.Text)
ListBox1.Items.Add("============================================")
End Sub
End Class
Not sure what your code was doing, but based on your requirements:
Public baseFemale As Integer = 20182000
Public baseMale As Integer = 20183000
Public autoNumber As Integer = 0
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Number as Integer;
autoNumber = autoNumber + 1
If Me.cboGender.SelectedItem = "Female" Then
Number = baseFemale + autoNumber
Else
Number = baseMale + autoNumber
Else
'Add Items To ListBox'
ListBox1.Items.Add("Student number: " & Number & i)
ListBox1.Items.Add(txtSurname.Text & " , " & txtFullName.Text)
ListBox1.Items.Add(txtContact.Text)
ListBox1.Items.Add("============================================")
End Sub
Additionally you may want to check for autoNumber exceeding 999 - but I leave that as an exercise for you.

Changing the color of a label's backcolor with a variable for the label's name

so I have a problem regarding trying to change the back colour of a label. I have 49 labels in a game we are making at school. Each label is named from 1 to 49 as "LabelTile1" "LabelTile2" "LabelTile3" etc. I am now trying to connect the player's score and "LabelTile" to create eg "LabelTile9" I got that much working but then I made a variable called LabelTileNameGenerator to store the "LabelTile9" variables created and then use
LabelTileNameGenerator.BackColor =System.Drawing.ColorTranslator.FromOle(&HC0FFC0)
But I get told thatBackColor is not a member of string.
Is there a better way of doing this than to write 150 lines of code together for each possible score and to then light up that tile?`Public Class Form1
Dim RoundCounter As Integer
Dim Player1Score As Integer
Dim Player2Score As Integer
Dim LabelTileNameGenerator
Dim hello As Object
Private Sub ButtonRollDice_Click(sender As Object, e As EventArgs) Handles ButtonRollDice.Click
Dim Rolled, Rolled2, RolledTotal As Integer
Dim oDice As New Random()
Dim Player As String
Rolled = oDice.Next(1, 7)
Rolled2 = oDice.Next(1, 7)
RolledTotal = Rolled + Rolled2
If RoundCounter Mod 2 = 0 Then
Player = 1
LabelRolledScores.Text = "Player " & Player & " got a " & Rolled & " and a " & Rolled2 & " together that gives you " & RolledTotal
Player1Score = Player1Score + RolledTotal
LabelP1Score.Text = "Player 1 current score : " & Player1Score
'.Name function used before it is set to a value
hello = "LabelTile" & Player1Score
LabelTileNameGenerator = hello
LabelTileNameGenerator.BackColor = System.Drawing.ColorTranslator.FromOle(&HC0FFC0)
End If
If RoundCounter Mod 2 = 1 Then
Player = 2
LabelRolledScores.Text = "Player " & Player & " got a " & Rolled & " and a " & Rolled2 & " together that gives you " & RolledTotal
Player2Score = Player2Score + RolledTotal
LabelP2CurrentScore.Text = "Player 2 current score : " & Player2Score
End If
RoundCounter = RoundCounter + 1
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
RoundCounter = 0
Player1Score = 1
Player2Score = 1
End Sub
End Class
Image of Naming
Image of GUI
Accessing all these labels by name is not a good option (creating them with names in the first place is not a good option either, but this is another pair of shoes). But you can still do that. The problem you are encountering is that you want to change something of the label but you only have the label's name. And of course, a name does not have a background color.
You could do something like this:
'We assume that this control exists and that it is a label. If you cannot assert that, you
'should add appropriate exception handling.
Dim tileLabel = CType(Me.Controls("LabelTile" & Player1Score), Label)
tileLabel.BackColor = '...
This code snippet finds the control with the given name ("LabelTile" & Player1Score) in the current form's controls collection. The type of the returned object is Control. If you just want to change the background color, you can leave the cast away (because Control has a BackColor). If you want to access a Label-specific property, you need to cast the returned object to type Label as shown in the snippet. Without the cast, it would look like this:
Dim tileLabel = Me.Controls("LabelTile" & Player1Score)
tileLabel.BackColor = '...

enter cash payed after i`m done choosing my order

Im using visual basic language on visual studio 2010.I want to be asked to enter the cash payed after im done picking the order, now it asks to enter cash after every item i choose.
below you'll find the code and screenshots
Dim choice As String
Dim price As Double
Dim quantity As Integer
Dim total As Double
Dim tpayable As Double
Dim cash As Double
Dim change As Double
Dim spaces As String = Space(4)
Private Sub menue_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim spaces As String = Space(4)
End Sub
Private Sub badd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles badd.Click
quantity = InputBox("enter item quantity", "quantity")
If RadioButton1.Checked Then
choice = "Potato soup"
price = "80"
ElseIf RadioButton2.Checked Then
choice = "Salmon roll"
price = "100"
ElseIf RadioButton3.Checked Then
choice = "Smoked salmon potatos"
price = "75"
End If
If RadioButton4.Checked Then
choice = "Lasagna"
price = "250"
ElseIf RadioButton5.Checked Then
choice = "Cheese burger"
price = "120"
ElseIf RadioButton6.Checked Then
choice = "Pizza"
price = "450"
ElseIf RadioButton7.Checked Then
choice = "ugali & sukuma"
price = "80"
ElseIf RadioButton8.Checked Then
choice = "Chicken fried noodles"
price = "150"
End If
If RadioButton9.Checked Then
choice = "Chocolate fudge cake"
price = "250"
ElseIf RadioButton10.Checked Then
choice = "Ice cream"
price = "150"
ElseIf RadioButton11.Checked Then
choice = "Carrot Cake"
price = "230"
End If
If RadioButton12.Checked Then
choice = "Black tea"
price = "80"
ElseIf RadioButton13.Checked Then
choice = "White tea"
price = "80"
ElseIf RadioButton14.Checked Then
choice = "Coffee"
price = "80"
End If
If RadioButton15.Checked Then
choice = "Coke"
price = "60"
ElseIf RadioButton16.Checked Then
choice = "Milkshake"
price = "110"
ElseIf RadioButton17.Checked Then
choice = "Fanta"
price = "60"
End If
total = quantity * price
tpayable += total
txttpayable.Text = Str(tpayable)
cash = InputBox("enter cash payed")
txtcgiven.Text = Str(cash)
change = cash - tpayable
txtchange.Text = Str(change)
ListBox1.Items.Add(String.Concat(choice & spaces & price & spaces & quantity & spaces & total & spaces & tpayable))
End Sub
screenshot
The application can't read your mind. It can only react to some input from you. You need to handle an appropriate event to let the application know that you have made all the appropriate selections and so it needs to prompt. Looking more closely at your code, it appears that you have several groups of RadioButtons. Assuming that the user must select one option from each group, you can handle the CheckedChanged event of all the RadioButtons and then check whether one is checked from each group. Here's a simplified example using two groups of two that you can extend to any number of groups and controls:
Private Sub RadioButtons_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged,
RadioButton2.CheckedChanged,
RadioButton3.CheckedChanged,
RadioButton4.CheckedChanged
If Panel1.Controls.OfType(Of RadioButton)().Any(Function(rb) rb.Checked) AndAlso
Panel2.Controls.OfType(Of RadioButton)().Any(Function(rb) rb.Checked) Then
'A selection has been made from each group.
End If
End Sub
This assumes that RadioButton1 and RadioButton2 are on Panel1 and RadioButton2 and RadioButton3 are on Panel2. As I said, there can be as many groups as you like and each group can contain as many options as you like. Each group can be on a Panel, a GroupBox or some other container.

Drink Vending Machine Code

Hello Stackflow community,
I'm currently taking a class in Visual Basic and I'm in need of some assistance. I am creating a program that simulates a Drink Vending Machine using an array. The instructions follow:
Create an application that simulates a soft-drink vending machine. The application should let the user select one of the following soft drinks:
Cola ($1.00 each)
Root Beer ($1.00 each)
Lemon Lime Soda ($1.00 each)
Grape Soda ($1.50 each)
Cream Soda ($1.50 each)
When the application starts, the vending machine will have 20 of each type of soft drink. Each time the user selects a drink, the application should subtract 1 from the quantity of the selected drink. It should also update and display the total amount of sales. If the user selects a drink that is sold out, a message should be displayed indicating so.
In the application’s code, create a structure that has fields for the following data:
Drink name
Drink cost
Number of drinks in machine
The program should create an array of five structure objects. Each element of the array should keep data for a specific type of soft drink.
I can't figure out how to make my buttons work to decrement the quantity labels and then add each click to the label total. Please help.
Public Class Form1
' Class-level declarations
Const intMAX_SUBSCRIPT As Integer = 4 ' Upper subscript
Dim strProdNames(intMAX_SUBSCRIPT) As String ' Product Names
Dim decPrice(intMAX_SUBSCRIPT) As Decimal ' Drink Price
Dim intProdNums(intMAX_SUBSCRIPT) As Integer ' Product Numbers
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Initialize the arrays with the product data.
InitArrays()
End Sub
Private Sub InitArrays()
' Initialize the arrays.
' First Product
strProdNames(0) = "Cola"
decPrice(0) = 1D
intProdNums(0) = 20
' Second Product
strProdNames(1) = "Root Beer"
decPrice(1) = 1D
intProdNums(1) = 20
' Third Product
strProdNames(2) = "Lemon Lime"
decPrice(2) = 1D
intProdNums(2) = 20
' Fourth Product
strProdNames(3) = "Grape Soda"
decPrice(3) = 1.5D
intProdNums(3) = 20
' Fifth Product
strProdNames(4) = "Cream Soda"
decPrice(4) = 1.5D
intProdNums(4) = 20
End Sub
Private Sub btnCola_Click(sender As Object, e As EventArgs) Handles btnCola.Click
Dim intCount As Integer = 20 ' Loop Counter
intCount -= 1 ' Decrement drink count
If intCount > 0 Then
lblTotal.Text = decPrice(0).ToString("c")
End If
End Sub
You need to decrement the cola count, which is in the array.
Private Sub btnCola_Click(sender As Object, e As EventArgs)
If intProdNums(0) > 0 Then
intProdNums(0)-=1 ' decrement cola drink count
End If
' show results here...
End Sub