procedural logic calculating averages using visual basic 2010 - vb.net

I am trying to calculate an average using Visual Basic 2010 and display this average in a message window. Whilst debugging (commenting out code and trying different variables being sent to the message box as string) I got the message window to appear, but with no data returned.
As I have the code now, I do not receive any errors, but I can't even get the message box to appear.
Basically the program has the user enter a number of books they have read which is then used to calculate a point total based on the amount of books read. The exercise asks to keep a average of all the books read.
Public Class BookPoints
'Declare module level variables for summary information
Private PointInteger, BookAmountInteger, SummaryBookTotal, ReaderCount As Integer
Private Sub ExitToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ExitToolStripMenuItem.Click
'Exit the program
Me.Close()
End Sub
Private Sub ClearToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles ClearToolStripMenuItem.Click
With NameTextBox2
.Clear()
.Focus()
.Select()
End With
BooksTextBox1.Clear()
PointsTextBox3.Clear()
End Sub
Private Function Points(ByVal BookAmountInteger As Integer) As Integer
'Calculate point total
If BookAmountInteger <= 3 Then
Return BookAmountInteger * 10
ElseIf BookAmountInteger >= 4 AndAlso BookAmountInteger <= 6 Then
Return 30 + (BookAmountInteger - 3) * 15
Else
Return 75 + (BookAmountInteger - 6) * 20
End If
End Function
Private Sub PointsToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles PointsToolStripMenuItem.Click
'calculate points and display total
Try
PointInteger = Integer.Parse(BooksTextBox1.Text)
PointsTextBox3.Text = Points(PointInteger).ToString()
Catch BookAmountException As FormatException
MessageBox.Show("Amount of books read must numeric.", _
"Data Entry Error", _
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
With BooksTextBox1
.Clear()
.Focus()
.Select()
End With
'calculate average of books read
Dim Total As Decimal
Total = Decimal.Parse(BooksTextBox1.Text)
If Total <> 0 Then
Total += SummaryBookTotal
ReaderCount += 1
End If
End Try
End Sub
Private Sub SummaryToolStripMenuItem_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles SummaryToolStripMenuItem.Click
Dim AverageBooks As Decimal
Dim MessageString As String
If ReaderCount > 0 Then
AverageBooks = SummaryBookTotal / ReaderCount
MessageString = "Average books read: " &
SummaryBookTotal.ToString()
MessageBox.Show(MessageString, "Average of Books Read", _
MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
End Class

Related

Saving an array to file

I been trying to save an array to file but I can only create the text file but no text shows up in actual file. The loop doesn't work the way I want to. I need to store the Cust array into text file.
Dim car(4) As Decimal
Dim Cust(4) As String
'Declare module-level constants.
Const PER_DAY_Integer As Integer = 15
Const PER_MILE_Decimal As Decimal = 0.12D
Private Sub CalcButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalcButton.Click
'Calculate the rental charges
Cust(0) = NameTextBox.Text
Cust(1) = AddressTextBox.Text
Cust(2) = CityTextBox.Text
Cust(3) = ZipTextBox.Text
Cust(4) = StateTextBox.Text
Try
car(0) = Decimal.Parse(BeginTextBox.Text)
Try
car(1) = Decimal.Parse(EndTextBox.Text)
Try
car(2) = Integer.Parse(DaysTextBox.Text)
'Calculate the number of miles driven and the charges
car(3) = car(1) - car(0)
car(4) = (car(3) * PER_MILE_Decimal + car(2) * PER_DAY_Integer)
'Display the results
TotalTextBox.Text = car(4).ToString("C")
MilesTextBox.Text = car(3).ToString("N1")
Catch ex As Exception
MessageBox.Show("Input Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
DaysTextBox.Focus()
End Try
Catch ex As Exception
MessageBox.Show("Input Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
EndTextBox.Focus()
End Try
Catch ex As Exception
MessageBox.Show("Input Error", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
BeginTextBox.Focus()
End Try
End Sub
Private Sub ClearButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearButton.Click
'Clear the form
AddressTextBox.Clear()
CityTextBox.Clear()
StateTextBox.Clear()
ZipTextBox.Clear()
BeginTextBox.Clear()
EndTextBox.Clear()
DaysTextBox.Clear()
TotalTextBox.Clear()
MilesTextBox.Clear()
With NameTextBox
.Clear()
.Focus()
End With
End Sub
Private Sub ExitButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExitButton.Click
'End the program
Me.Close()
End Sub
Private Sub PrintButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrintButton.Click
'Print the form
PrintForm1.PrintAction = Printing.PrintAction.PrintToPreview
PrintForm1.Print()
End Sub
Private Sub readBtn_Click(sender As Object, e As EventArgs) Handles readBtn.Click
End Sub
Private Sub WriteBtn_Click(sender As Object, e As EventArgs) Handles WriteBtn.Click
Dim outFile As IO.StreamWriter
Dim int As Integer = 0
Dim count As Integer = 0
outFile = IO.File.CreateText("Cust.txt")
Do While int < count
outFile.WriteLine(Cust(1)(int))
int += 1
Loop
outFile.Close()
End Sub
End Class
You were asked where it failed when you debug and you obviously haven't even bothered to debug or you'd have seen the issue. Look at this from your code:
Dim int As Integer = 0
Dim count As Integer = 0
outFile = IO.File.CreateText("Cust.txt")
Do While int < count
outFile.WriteLine(Cust(1)(int))
int += 1
Loop
Is int ever going to be less than count?
You can replace the entire contents of that last event handler with one line:
IO.File.WriteAllLines("Cust.txt", Cust)
Of course, you should not be using file names alone but rather a file path, but that's another issue.

Not Calculating or Showing MessageBox

I have an assignment I have been working on in VB. I have attached the assignment below:
(I would've attached the image but I cannot because I am a new user)
Assignment Question
(http://i.imgur.com/LPZre2F.jpg)
I have written all of the code but for some reason I cannot get the calculate button to calculate anything. Nor, can I get the messagebox to show in the Calculate button when there is no input in the NameTextBox or the PieceTextBox.
Can someone spot something that I am missing on why this may not be working?
Public Class Form1
'Declare Variables
Dim Pieces As Integer
Dim AmtEar As Decimal
Dim NoPieces As Decimal = 0
Dim totPay As Decimal = 0
Dim avgPay As Decimal = 0.0
'Declare Confirm Message Variable
Dim confirmOpt As DialogResult
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Try
'Declare constant rates paid out
Const priceRate1 As Decimal = 0.5
Const priceRate2 As Decimal = 0.55
Const priceRate3 As Decimal = 0.6
Const priceRate4 As Decimal = 0.65
'Check the blank fields (name and number of pieces)
If NameTextBox.Text = "" Then
MessageBox.Show("Please Enter Name:")
Else
If PieceTextBox.Text = "" Then
MessageBox.Show("Please Enter Number of Pieces Produced")
Else
'Count number of pieces
NoPieces += 1
'Read number of pieces
Pieces = Integer.Parse(PieceTextBox.Text)
'Use select case for given constraints
'calculate earned amount for each
Select Case Pieces
Case 1 To 199
AmtEar = priceRate1 * Pieces
totPay += AmtEar
Case 200 To 399
AmtEar = priceRate2 * Pieces
totPay += AmtEar
Case 400 To 599
AmtEar = priceRate3 * Pieces
totPay += AmtEar
Case Is >= 600
AmtEar = priceRate4 * Pieces
totPay += AmtEar
Case Else
MessageBox.Show("Number of Pieces Produced Must Be Numeric")
End Select
'Display amount earned
AmtTextBox.Text = AmtEar.ToString("C")
End If
End If
'Exception for wrong input
Catch ex As FormatException
MessageBox.Show("Enter Valid Data", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information)
End Try
End Sub
Private Sub SummaryButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SummaryButton.Click
'calculates summary total
If (NoPieces >= 1) Then
'calculate and update total pieces, total pay and average pay
avgPay = totPay / NoPieces
TotalProducedTextBox.Text = NoPieces.ToString()
TotlPayTextBox.Text = NoPieces.ToString("C")
AveragePayTextBox.Text = avgPay.ToString("C")
Else
'Otherwise display message
MessageBox.Show("Enter at Least One Employee Data", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Private Sub ClearButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearButton.Click
'Clear name and number of pieces
NameTextBox.Clear()
PieceTextBox.Clear()
AmtTextBox.Clear()
End Sub
Private Sub ClearAllButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ClearAllButton.Click
'If no data is available
If NoPieces = 0 Then
MessageBox.Show("No Data Available To Delete")
Else
'Confirm option message
confirmOpt = MessageBox.Show("Are You Sure You Want To Delete Summary", "Confirm", MessageBoxButtons.YesNo)
'Check if yes then clear all inputs and totals
If confirmOpt = DialogResult.Yes Then
avgPay = 0
totPay = 0
NoPieces = 0
NameTextBox.Clear()
PieceTextBox.Clear()
AmtTextBox.Clear()
TotalProducedTextBox.Clear()
TotlPayTextBox.Clear()
AveragePayTextBox.Clear()
End If
End If
End Sub
End Class
You are missing the Click-handle for that button.
Change this:
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
to something like this:
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click

How to make an inputbox and text file appear in Visual Basic?

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 program keeps looping an inputbox. How do I get out of it?

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 inputbox, type the numeric value, however, it continues to loop over and over again. I don't get why this is happening. Please refer to the cmdCheckOut_Click subroutine in the code below. I think that's where I'm getting my error.
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
Dim decimal1 As Decimal
Dim decimal3 As Decimal
Dim decimal4 As Decimal
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 str1 As String = ""
If (purchaseCount = 0) Then
MsgBox("You have not ordered any items!", MsgBoxStyle.Exclamation, "Order Error")
Else
Do Until ((IsNumeric(str1) And (Decimal.Compare(decimal3, Decimal.Zero) <= 10)) And (Decimal.Compare(decimal3, (10D)) >= 0))
str1 = InputBox("Enter your tax rate as a %" & vbCrLf & "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 decimal3 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(purchaseTitle(num1))
Dim decimal1 As Decimal = Decimal.Add(Nothing, 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 decimal4 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
Basically it looks like you're using Decimal.Compare wrong., See if this helps:
Do
str1 = InputBox("Enter your tax rate as a %" & vbCrLf & "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 decimal3 As Decimal = Convert.ToDecimal(str1)
If decimal3 < 0 Orelse decimal3 > 10 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 Until (IsNumeric(str1) Andalso (decimal3 <= 10 Andlso decimal3 >= 0))

Code won't pop up in the Textboxes of the Customer Receipt Form

The Problem is the coding won't pop up in the Textboxes of the Customer Receipt Form.
Any Solutions?
'This is the coding for the for the SelfCheckOutForm.
'======================================================================================================================================
Option Strict On
'Declare the UPC Structure
Structure UPC
Friend UPCString As String
Friend ProductString As String
Friend DesriptString As String
Friend WeightDecimal As Decimal
Friend PriceDecimal As Decimal
End Structure
Public Class SelfCheckout
'declare structure variables
Dim PriceArray(4) As UPC
'====================================================================================================================================
'declare variables
Friend TotalPriceDecimal As Decimal
Friend TotalWeightDecimal As Decimal
Friend TotalItemsInteger As Integer
Friend MessageString As String
Friend totalString As String
Friend numberOfItemsString As String
Friend weightOfItemsString As String
'=======================================================================================================================================
'ListBox Coding with Arrays
Private Sub SelfCheckout_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'Load My List Box with the UPC Codes
UPCListBox.Items.Add("12345")
UPCListBox.Items.Add("23451")
UPCListBox.Items.Add("34512")
UPCListBox.Items.Add("45123")
UPCListBox.Items.Add("51234")
'-------------------------------------------------------------------------------
'Create my UPC Array Values
PriceArray(0).UPCString = "12345"
PriceArray(1).UPCString = "23451"
PriceArray(2).UPCString = "34512"
PriceArray(3).UPCString = "45123"
PriceArray(4).UPCString = "51234"
'-------------------------------------------------------------------------------
'Create my Product Array Values
PriceArray(0).ProductString = "Computer Tower"
PriceArray(1).ProductString = "Laptop"
PriceArray(2).ProductString = "Flatscreen Monitor"
PriceArray(3).ProductString = "Wifi Router"
PriceArray(4).ProductString = "All-In-One Printer"
'------------------------------------------------------------------------------
'Create my Description Array Variables
PriceArray(0).DesriptString = "A computer that can do basic office work."
PriceArray(1).DesriptString = "A computer you can take with you."
PriceArray(2).DesriptString = "A Computer monitor to go with the tower."
PriceArray(3).DesriptString = "You can now go online anywhere in your house!"
PriceArray(4).DesriptString = "It has a Scanner and a fax machine built in!"
'-------------------------------------------------------------------------------
'Create my Price Array Values
PriceArray(0).PriceDecimal = 499.95D
PriceArray(1).PriceDecimal = 550.5D
PriceArray(2).PriceDecimal = 170.95D
PriceArray(3).PriceDecimal = 70.65D
PriceArray(4).PriceDecimal = 199.95D
'------------------------------------------------------------------------------
'Create my Weight Array Values
PriceArray(0).WeightDecimal = 15
PriceArray(1).WeightDecimal = 5
PriceArray(2).WeightDecimal = 8
PriceArray(3).WeightDecimal = 3
PriceArray(4).WeightDecimal = 18
End Sub
'===============================================================================================================================================
'Textbox.text from UPC listbox coding
Private Sub UPCListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UPCListBox.SelectedIndexChanged
'Show UPC in UPC TextBox
UPCTextBox.Text = UPCListBox.Text
'Looking up the Product
'Table Look up Do/Loop
Dim myBoolean As Boolean 'True = Found the Product
Dim indexInteger As Integer = 0
Do Until myBoolean Or indexInteger > 4
With Me
If UPCTextBox.Text = PriceArray(indexInteger).UPCString Then
ProductTextBox.Text = (PriceArray(indexInteger).ProductString) 'Fills Product TextBox
DescriptTextBox.Text = (PriceArray(indexInteger).DesriptString) 'Fill Description TextBox
WeightTextBox.Text = FormatNumber(PriceArray(indexInteger).WeightDecimal) 'Fill Weight Textbox
PriceTextBox.Text = FormatCurrency(PriceArray(indexInteger).PriceDecimal) 'Fill Price Textbox
myBoolean = True
Else
indexInteger += 1
End If
End With
Loop
End Sub
'====================================================================================================================================================
'Message Box Coding
Private Sub PurchaseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PurchaseButton.Click
If PurchaseButton.Enabled And PriceTextBox.Text <> "" Then
'Calculate the quantities
TotalItemsInteger += 1 'counts the purchases made
TotalPriceDecimal += CDec(PriceTextBox.Text) 'Adds the purchases together
TotalWeightDecimal += CDec(WeightTextBox.Text) 'Adds the wieghts of purchases together
'----------------------------------------------------------------------------------------------------------------
'Building Meassage Box for purchase button
numberOfItemsString = TotalItemsInteger.ToString()
totalString = TotalPriceDecimal.ToString("C")
weightOfItemsString = TotalWeightDecimal.ToString("N")
MessageString = "Total Items: " & numberOfItemsString &
Environment.NewLine & "Total Weight: " & weightOfItemsString &
Environment.NewLine & "Total Price: " & totalString
'------------------------------------------------------------------------------------------------------------------
'Display Message box
MessageBox.Show(MessageString, "Items Purchased:", MessageBoxButtons.OK)
End If
End Sub
Private Sub CloseOrderButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseOrderButton.Click
CustomerReceiptForm.ShowDialog()
End Sub
End Class
'Programmer: A.Rose
'Date: 10/8/13
'Description: The CustomerReceiptForm provides information on how many items, the total weight and price
'of the combined purchase.
'This is The coding for the CustomerReceiptForm.
'===============================================================================================================================================
Option Strict On
Public Class CustomerReceiptForm
'Function of the Enjoy your Purchase Button
Private Sub CloseBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CloseBtn.Click
Me.Close()
SelfCheckout.Close()
End Sub
'=================================================================================================================================================
'coding for filling in the Textboxes with the appropriate information
'-----------------------------------------------------------------------
'Total Price of Purchases
Private Sub TotalItemsTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TotalItemsTextBox.TextChanged
TotalItemsTextBox.Text = SelfCheckout.TotalItemsInteger.ToString()
End Sub
'-----------------------------------------------------------------------
'Total Weight of Purchases
Private Sub TotalWeightTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TotalWeightTextBox.TextChanged
TotalWeightTextBox.Text = SelfCheckout.TotalWeightDecimal.ToString("N")
End Sub
'------------------------------------------------------------------------
'Total Price of Purchases
Private Sub TotalCostTextBox_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TotalCostTextBox.TextChanged
TotalCostTextBox.Text += SelfCheckout.TotalPriceDecimal.ToString("C")
End Sub
'-------------------------------------------------------------------------
End Class
Classes are like blueprints - they tell what something will do when (if) it is ever created. Instances of those classes actually do those things and are what is used in code. You have a CustomerReceiptForm but it is not shown anywhere that you ever created an instance if it like this:
Friend frmCustRec as New CustomerReceiptForm
MAYBE that happens elsewhere in code not posted, but the references in the 2 classes here indicate otherwise. To show it as in the CloseOrderButton_Click it would be
frmCustRec.ShowDialog
The same is true the SelfCheckout class - you need an instance.
BTW, your UPS structure would work great as a private class (think of it as a SelfCheckout helper class). As such, PriceArray could become a List (Of UPC) or Dictionary (of itemKey, UPC) which would make it easier to manage and read.