Alright, so I have edited my code and now when I'm trying to run it I'm getting this error.
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll
Additional information: Conversion from string "Holden 308" to type 'Integer' is not valid.
Additional information: Conversion from string "JD Catepillar Track" to type 'Integer' is not valid.
So both errors are happening in the HeavyStockItem class with the overloading New classes. Wondering if anyone can help me out with understanding why it's doing that.
Option Strict On
Public Class Form1
Dim StockItem1 As StockItem
Dim StockItem2 As CarEngine
Dim StockItem3 As CarEngine
Dim StockItem4 As StockItem
Dim StockItem5 As HeavyStockItem
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
StockItem1 = New StockItem("Screwdriver Set", 42)
StockItem2 = New CarEngine(8025, "Madza B6T", 1252, 800, "Z4537298D")
'StockItem3 = New CarEngine("Holden 308", 958, 1104, "P74623854S")
StockItem4 = New StockItem(8002, "Trolley Jack", 127)
'StockItem5 = New HeavyStockItem("JD Catepillar Track", 3820, 2830)
End Sub
Private Sub btnListStock_Click(sender As Object, e As EventArgs) Handles btnListStock.Click
txtOutput.Clear()
ShowOutput(StockItem1)
ShowOutput(StockItem2)
'ShowOutput(StockItem3)
ShowOutput(StockItem4)
'ShowOutput(StockItem5)
End Sub
Public Sub ShowOutput(ByVal Output As StockItem)
txtOutput.Text &= Output.Print()
txtOutput.Text &= vbCrLf
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnEnd.Click
End
End Sub
End Class
Public Class StockItem
Friend CostPrice As Integer
Friend LastStockNumber As Integer
Friend StockNumber As Integer
Friend Description As String
Friend Shared LastStockItem As Integer = 10000
Overridable Function Print() As String
Dim Result As String = ""
Result &= "Stock No: " & StockNumber
Result &= vbCrLf
Result &= "Description: " & Description
Result &= vbCrLf
Result &= "Cost Price: " & CostPrice
Result &= vbCrLf
Return Result
End Function
Public Sub New(ByVal StockNumber As Integer, Description As String, ByVal CostPrice As Integer)
Me.New(Description, CostPrice)
Me.StockNumber = StockNumber
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer)
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
Me.Description = Description
Me.CostPrice = CostPrice
End Sub
Public Sub GetCostPrice()
End Sub
End Class
Public Class HeavyStockItem
Inherits Assessment3.StockItem
Friend Weight As Integer
Public Function GetWeight() As String
Return Me.GetWeight
End Function
Public Sub New(ByVal StockNumber As Integer, ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer)
MyBase.New(StockNumber, Description, CostPrice)
Me.Weight = Weight
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer)
MyBase.New(Description, CostPrice, Weight)'' Where the error is occurring
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
End Sub
End Class
Public Class CarEngine
Inherits Assessment3.HeavyStockItem
Friend EngineNumber As String
Overrides Function Print() As String
Dim Result As String = ""
Result &= "Stock No: " & StockNumber
Result &= vbCrLf
Result &= "Description: " & Description
Result &= vbCrLf
Result &= "Cost Price: " & CostPrice
Result &= vbCrLf
Result &= "Weight: " & Weight
Result &= vbCrLf
Result &= "Engine Number: " & EngineNumber
Result &= vbCrLf
Return Result
End Function
Public Sub New(ByVal StockNumber As Integer, ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer, ByVal EngineNumber As String)
MyBase.New(StockNumber, Description, CostPrice, Weight)
Me.EngineNumber = EngineNumber
End Sub
Public Sub New(ByVal Description As String, ByVal CostPrice As Integer, ByVal Weight As Integer, ByVal EngineNumber As String)
MyBase.New(Description, CostPrice, Weight)
LastStockNumber += Rnd()
Me.StockNumber = LastStockNumber
End Sub
End Class
Any help provided would be great. Just thought it'd be easier to provide the full code instead of just putting only the little bits that I really needed, incase if people asked about the other parts of the code. Thanks for reading and providing help if you provided help.
Since your code was confusing to me I relied mostly on the exception.
It basically says that it cant convert the string into an integer. Here's something that could cause the same problem.
Dim Number As String = "10"
'Few Lines of code.
Number = 11
whats basically happening is that when you declare a variable as a string the value of it HAS to be in double quotes as you see when it was declared. Now then we try to change the value to 11 while adding no double quotes, therefor it thought you were changing it to an integer and gave the error.
I looked through the code and saw this, maybe this is causing it:
Me.Description = Description <--- No quotes!!!
I'm probably wrong though since i didn't really understand the code.
Related
I want to unzip a specific file with a external Program in VB.NET but, I don't know how to do that.
This is my attempt.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Process.Start("7z.exe","-e" Textbox1.Text + Combobox1.Text )
End Sub
Instead of using the 7z.exe use the DLL they provide.
Public Class ArchivationHandling
Private Declare Function SevenZip Lib "7-zip32.dll" (ByVal hwnd As Integer, ByVal strCmdLine As String, ByVal strOutput As String, ByVal dwSize As Integer) As Long
Private bJobCompleted As Boolean = False
Private Const ZIP_EXTENSION As String = ".zip"
Private Const SEVEN_ZIP_PAR As String = vbNullString
Private Function Decompress(ByVal strZipPath As String, ByVal strOutPut As String) As Boolean
Dim strZipComm As String = "x -o" & strOutPut & " " & strZipPath & ZIP_EXTENSION & " -hide"
Try
SevenZip(0, strZipComm, SEVEN_ZIP_PAR, 0)
bJobCompleted = True
Catch ex As Exception
Logger.WriteLogEntry(4, "Decompression failed for file: " & strZipPath & " " & ex.Message.ToString)
End Try
Return bJobCompleted
End Function
Public ReadOnly Property Decompression(ByVal strZipFilePath As String, ByVal strOutput As String) As Boolean
Get
Return Decompress(strZipFilePath, strOutput)
End Get
End Property
End Class
This is an example of what I use in one of my applications.
You just provide the input file and output.
At first, I will say I'm new here so I may not explain my problem properly. I use VB.Net Windows Forms applications. In this project I have to call a sub procedure from another class to display a report when the button is clicked. sub doesn't return a value I know that and I am used to that whenever I have a sub I will display the value inside the sub but I can't write the name of the text box in the other class . These are my codes I hope you can understand what I mean from it .
Public Class Form1
Dim aobj As New Allowance
Dim nam As String
Dim ID, year, allowance, total As Double
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
allowance = txtamount.Text
total = aobj.calculatetotal(allowance)
txtcalculate.ForeColor = Color.Red
txtcalculate.Text = FormatNumber(total)
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
ID = txtid.Text
year = txtyear.Text
nam = txtname.Text
txtreport.ForeColor = Color.Blue
txtreport.Text = aobj.displayreport(nam, ID, year, total)
End Sub
End Class
Class Allowance
Function calculatetotal(ByVal a As Double) As Double
Return (12 * 5 * a)
End Function
Sub displayreport(ByVal nam As String, ByVal id As Double, ByVal y As Double, ByVal tot As Double)
(" The Student " & nam & " with ID: " & id & " will receivce a total allowance of " & tot & " for five years of study in YUC")
End Sub
End Class
You need to change displayreport to a function and return that string if you want to assign that string to txtreport.Text. Try changing it to:
Public Function displayreport(ByVal nam As String, ByVal id As Double, ByVal tot As Double) As String
Return " The Student " & nam & " with ID: " & id & " will receivce a total allowance of " & tot & " for five years of study in YUC"
End Function
I also removed "y as double" because it isn't being used
I'm creating a Quiz Application in VB and the quiz app reads the questions from a text file which is already created and it has got some questions in it.
1
Q.Who won the WorldCup last time?
I Don't know
May be he knows
Who knows
Who cares?
2
Question 2
Answer A
Answer B
Answer C
Answer D
3
Question 3
Ans 1
Ans 2
Ans 3
Ans 4
The first line is the question number,the second line is the question,lines 3 - 6 represents the answer choices.Now I have created a Form for quiz and when the next button is pressed it should display the next question i.e,After the first question it should go to Question 2 and print accordingly.But unfortunately i'm unable to calculate the logic to go to next question.
Public Class Quiz
<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
Private Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As Integer, ByVal lParam As Integer) As IntPtr
End Function
Dim SCORE As Integer = 0
Dim val As Integer = 30
Dim QUES As Integer = 0
Dim Line As Integer = 1
Dim allLines As List(Of String) = New List(Of String)
Dim TextFilePath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Quiz.txt")
Private Sub Quiz_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ProgressBar1.Minimum = 0
ProgressBar1.Maximum = 30
Timer1.Enabled = True
Next_Prev_Ques(Line + QUES)
End Sub
Public Function Next_Prev_Ques(quesno As Integer) As Integer
Line = quesno
Using file As New System.IO.StreamReader(TextFilePath)
Do While Not file.EndOfStream
allLines.Add(file.ReadLine())
Loop
End Using
QUES = ReadLine(Line, allLines)
Label1.Text = ReadLine(Line + 1, allLines)
RadioButton1.Text = ReadLine(Line + 2, allLines)
RadioButton2.Text = ReadLine(Line + 3, allLines)
RadioButton3.Text = ReadLine(Line + 4, allLines)
RadioButton4.Text = ReadLine(Line + 5, allLines)
Return Line
End Function
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
ProgressBar1.Value += 1
val -= 1
Label2.Text = val & " Sec"
If ProgressBar1.Value = ProgressBar1.Maximum Then
Timer1.Enabled = False
End If
If ProgressBar1.Value > 25 Then
SendMessage(ProgressBar1.Handle, 1040, 2, 0)
End If
End Sub
Private Sub Quiz_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
Form1.Close()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MsgBox(Line + QUES + 5)
Next_Prev_Ques(Line + QUES + 4)
Me.Refresh()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Next_Prev_Ques(Line + QUES + 5)
End Sub
The function Next_Prev_Ques Should run accordingly but its not.Can anyone post the correct code?
Below is some code that uses serialization to get the same results. You can create a class called Questions and properties on it like questionnumber, question and answer, store the data into a xml file and retrieve them with string methods. Check the code below:
The code for the class
Public Class clsQuestions
Private _Number As String
Private _Question As String
Private _Answer As String
Public Property Number() As String
Get
Number = _Number
End Get
Set(ByVal Value As String)
_Number = Value
End Set
End Property
Public Property Question() As String
Get
Question = _Question
End Get
Set(ByVal Value As String)
_Question = Value
End Set
End Property
Public Property Answer() As String
Get
Answer = _Answer
End Get
Set(ByVal Value As String)
_Answer = Value
End Set
End Property
End Class
The code for the form
Imports System.IO
Imports System.Xml.Serialization
Public Class Form1
Dim numQuestions() As String
Dim questions() As String
Dim answersGroup() As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Label1.Text = ""
Label2.Text = ""
Label3.Text = ""
Main()
End Sub
Private Sub Main()
Dim p As New clsQuestions
p.Number = "1,2,3,4,5,6,7,8,9,10"
p.Question = "Question 1,Question 2,Question 3," &
"Question 4,Question 5,Question 6,Question 7," &
"Question 8,Question 9,Question 10"
p.Answer = "Answer 1.1,Answer 1.2,Answer 1.3,Answer 1.4;" &
"Answer 2.1,Answer 2.2,Answer 2.3,Answer 2.4;" &
"Answer 3.1,Answer 3.2,Answer 3.3,Answer 3.4;" &
"Answer 4.1,Answer 4.2,Answer 4.3,Answer 4.4;" &
"Answer 5.1,Answer 5.2,Answer 5.3,Answer 5.4;" &
"Answer 6.1,Answer 6.2,Answer 6.3,Answer 6.4;" &
"Answer 7.1,Answer 7.2,Answer 7.3,Answer 7.4;" &
"Answer 8.1,Answer 8.2,Answer 8.3,Answer 8.4;" &
"Answer 9.1,Answer 9.2,Answer 9.3,Answer 9.4;" &
"Answer 10.1,Answer 10.2,Answer 10.3,Answer 10.4"
'Serialize object to a text file.
Dim objStreamWriter As New StreamWriter("C:\Users\Username\Documents\Questions.xml")
Dim x As New XmlSerializer(p.GetType)
x.Serialize(objStreamWriter, p)
objStreamWriter.Close()
'Deserialize text file to a new object.
Dim objStreamReader As New StreamReader("C:\Users\Username\Documents\Questions.xml")
Dim p2 As New clsQuestions
p2 = x.Deserialize(objStreamReader)
objStreamReader.Close()
numQuestions = p2.Number.Split(",")
questions = p2.Question.Split(",")
answersGroup = p2.Answer.Split(";")
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
Static x As Integer
If x <= questions.Length - 1 Then
Label1.Text = ""
Label2.Text = ""
Label3.Text = ""
arrayIndex(x)
x += 1
End If
End Sub
Private Sub arrayIndex(ByVal num As Integer)
Label1.Text = numQuestions(num)
Label2.Text = questions(num)
Dim answers() As String
answers = answersGroup(num).Split(",")
For Each item As String In answers
Label3.Text &= item & Environment.NewLine
Next
End Sub
End Class
The code was working and then suddenly stopped for the newer Labels that I have added to the form. It seems like the Timer code that subtracts the time and adds to the AccTimeStg is not being called. The ArrayTimer works the Prefix text changes just fine so that timer is working. So the First two Labels I have on the form do as they are coded to do. I thought that when a change was made to a class and then a build was done the changes were made to all the objects that were using that class. I tested that theory as well Being new to using classes, It worked that way. I just don't understand how the old Labels are not affected but newer ones are not working.
Here is the code
Option Strict On
Imports System.Text
Imports System.IO
Imports System.Collections.Generic
Public Class TimeLogLabel
Inherits Label
Private m_VaraibleToSet As Boolean
<System.ComponentModel.Category("Control")> _
Public Property VaraibleToSet() As Boolean
Get
Return m_VaraibleToSet
End Get
Set(ByVal value As Boolean)
m_VaraibleToSet = value
End Set
End Property
Private m_PrefixText As String = "Prefix Text"
<System.ComponentModel.Category("Control")> _
Public Property PrefixText() As String
Get
Return m_PrefixText
End Get
Set(ByVal value As String)
m_PrefixText = value
End Set
End Property
Public Class LogTime
Private m_EventName As String
Public Property EventName() As String
Get
Return m_EventName
End Get
Set(ByVal value As String)
m_EventName = value
End Set
End Property
Private m_StartT As String
Public Property StartT() As String
Get
Return m_StartT
End Get
Set(ByVal value As String)
m_StartT = value
End Set
End Property
Private m_StopT As String
Public Property StopT() As String
Get
Return m_StopT
End Get
Set(ByVal value As String)
m_StopT = value
End Set
End Property
Private m_TSpan As String
Public Property TSpan() As String
Get
Return m_TSpan
End Get
Set(ByVal value As String)
m_TSpan = value
End Set
End Property
Public Sub New( _
ByVal m_EventName As String, _
ByVal m_StartT As String, _
ByVal m_StopT As String, _
ByVal m_TSpan As String)
EventName = m_EventName
StartT = m_StartT
StopT = m_StopT
TSpan = m_TSpan
End Sub
End Class
'***********************
Private Timer As Timer
Private ArrayTimer As Timer
Public StartTime As Date
Public StopTime As Date
Public AccTimeStg As String
Public TimeArray(19) As String
Private Ons As Boolean
Public Sub New()
Timer = New Timer
Timer.Interval = 1
AddHandler Timer.Tick, AddressOf Timer_Tick
ArrayTimer = New Timer
ArrayTimer.Interval = 100
ArrayTimer.Enabled = True
AddHandler ArrayTimer.Tick, AddressOf ArrayTimer_Tick
End Sub
Public TimeList As List(Of LogTime) = New List(Of LogTime)
Dim EventId As Integer
Public Sub StartTimer()
If Ons = False Then
Ons = True
EventId = EventId + 1
StartTime = Now
AddLog(TimeArray, PrefixText & ": Start Time " & StartTime)
TimeList.Add(New LogTime(PrefixText & " " & EventId, "Start Time " & StartTime, "", ""))
Timer.Enabled = True
Timer.Start()
End If
End Sub
Public Sub StopTimer()
If Ons = True Then
Ons = False
EventId = EventId + 1
StopTime = Now
AddLog(TimeArray, PrefixText & ": Stop Time " & StopTime & " Up Time " & AccTimeStg)
TimeList.Add(New LogTime(PrefixText & " " & EventId, "", "Stop Time " & StopTime, " Up Time " & AccTimeStg))
Timer.Enabled = False
Timer.Stop()
End If
End Sub
Public Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
Dim TimeSpan As TimeSpan = Now.Subtract(StartTime)
AccTimeStg = TimeSpan.Days & " : " & TimeSpan.Hours & " : " & TimeSpan.Minutes & " : " & TimeSpan.Seconds
End Sub
Private Sub ArrayTimer_Tick(ByVal sender As Object, ByVal e As EventArgs)
'''' Me.Text = String.Join("XX", TimeList)
' this is the normal Me.text
Me.Text = PrefixText & " " & AccTimeStg
End Sub
Private Sub AddLog(ByVal logAsArray() As String, ByVal newEntry As String)
For index As Integer = logAsArray.Length - 1 To 1 Step -1
logAsArray(index) = logAsArray(index - 1)
Next
logAsArray(0) = newEntry
End Sub
End Class
I have figured it out. With the help of #Ben N THX
Private WithEvents Timer As Timer
Private WithEvents ArrayTimer As Timer
was needed to use the handles
Public Sub Timer_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer.Tick
I am trying to figure out how to grab a value in a textbox (the price), that was put there with a temporary variable and an array, and change it into a decimal value so I can sum up the total sales and then sum up the total weight from another textbox using the same array. I have been working with this for about 5 hours now, with my book and searching online sites and nothing is working. I am stuck in the private sub purchase button procedure, (second from the bottom). My total items counter is working, and I made the subTotal Decimal and totalWeightDecimal counters also, to make sure the message box was working, but I want to change that += 1 into the correct code, I just can't find it. I tried the parseing, but it was a no go. Change textbox.textI included my entire code for someone to look at. I know I have too many private variables, just waiting to figure everything out before I get rid of them. Any help would be greatly appreciated. All in all, on this entire program I have spent a minimum of 15 hours. Thank you for your time and effort.
'Declare Item Structure.
Structure Item
Dim upcString As String
Dim nameString As String
Dim descriptionString As String
Dim weightString As String
Dim priceDecimal As Decimal
End Structure
'Declare the ItemPrices Structure
Public Structure ItemPrices
Dim itemdescriptionString As String
Dim itempriceDecimal As Decimal
Dim itemweightDecimal As Decimal
Dim itemupcInteger As Integer
End Structure
Public Class lab7Form
Private price1Decimal As Decimal
Private subTotalDecimal As Decimal
Private grandTotalDecimal As Decimal
Private totalDecimal As Decimal
Private totalItemsInteger As Integer
Private MessageString As String
Private totalWeightDecimal As Decimal
Dim myItem As Item
Private ItemPricesArray(3) As ItemPrices
Private Sub exitButton_Click(sender As System.Object, e As System.EventArgs) Handles exitButton.Click
If MsgBox("Click Yes to Exit, Click No to Cancel", MsgBoxStyle.YesNo, "You Decide") = MsgBoxResult.Yes Then
Me.Close()
End If
End Sub
Private Sub clearButton_Click(sender As System.Object, e As System.EventArgs) Handles clearButton.Click
'Clear the textbox values.
upcTextBox.Text = ""
descriptionTextBox.Text = ""
weightTextBox.Text = ""
priceTextBox.Text = ""
End Sub
Private Sub lab7Form_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'Load my itemsListbox with the items for the user.
itemsListBox.Items.Add("Notebook PC")
itemsListBox.Items.Add("Deskjet Printer")
itemsListBox.Items.Add("Color Ink Cartridge")
itemsListBox.Items.Add("Black Ink Cartridge")
'Load the ItemPricesArray values.
ItemPricesArray(0).itemdescriptionString = "Notebook PC"
ItemPricesArray(1).itemdescriptionString = "Deskjet Printer"
ItemPricesArray(2).itemdescriptionString = "Color Ink Cartridge"
ItemPricesArray(3).itemdescriptionString = "Black Ink Cartridge"
ItemPricesArray(0).itempriceDecimal = 1500D
ItemPricesArray(1).itempriceDecimal = 430D
ItemPricesArray(2).itempriceDecimal = 11D
ItemPricesArray(3).itempriceDecimal = 10D
ItemPricesArray(0).itemweightDecimal = 7D
ItemPricesArray(1).itemweightDecimal = 16D
ItemPricesArray(2).itemweightDecimal = 0.5D
ItemPricesArray(3).itemweightDecimal = 0.5D
ItemPricesArray(0).itemupcInteger = 111111111
ItemPricesArray(1).itemupcInteger = 222222222
ItemPricesArray(2).itemupcInteger = 333333333
ItemPricesArray(3).itemupcInteger = 444444444
End Sub
Private Sub itemsListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles itemsListBox.SelectedIndexChanged
descriptionTextBox.Text = itemsListBox.Text
'I am using a table lookup Do/Loop here.
Dim myBoolean As Boolean 'True = I found an items price.
Dim indexInteger As Integer = 0
Do Until myBoolean Or indexInteger > 3
With Me
If .descriptionTextBox.Text = ItemPricesArray(indexInteger).itemdescriptionString Then
.priceTextBox.Text = ItemPricesArray(indexInteger).itempriceDecimal.ToString("C")
.weightTextBox.Text = ItemPricesArray(indexInteger).itemweightDecimal.ToString()
.upcTextBox.Text = ItemPricesArray(indexInteger).itemupcInteger.ToString()
myBoolean = True
Else
indexInteger += 1
End If
End With
Loop
End Sub
Private Sub purchaseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles purchaseButton.Click
Dim DecNumber1 As Decimal
'Parse Numbers
DecNumber1 = Decimal.Parse(priceTextBox.Text)
If purchaseButton.Enabled And priceTextBox.Text <> "" Then
'Calculate the quantities
totalItemsInteger += 1 'I can't figure out how to total up the weights and prices when they are both local variables.
subTotalDecimal += DecNumber1
totalWeightDecimal += 1
'From Page 172 Put together what you want to appear in message boxes
Dim MessageString As String
Dim totalString As String
Dim numberOfItemsString As String
Dim weightOfItemsString As String
numberOfItemsString = totalItemsInteger.ToString()
totalString = subTotalDecimal.ToString("C")
weightOfItemsString = totalWeightDecimal.ToString("N")
MessageString = "Total Items : " & numberOfItemsString &
Environment.NewLine & "Total Weight: " & weightOfItemsString &
Environment.NewLine & "Subtotal: " & totalString
'Display the message box
MessageBox.Show(MessageString, "Items Purchased", MessageBoxButtons.OKCancel)
End If
End Sub
Private Sub totalButton_Click(sender As System.Object, e As System.EventArgs) Handles totalButton.Click
Dim numberofOrdersString As String
If totalButton.Enabled Then
numberofOrdersString = "Number of Orders: " & totalItemsInteger.ToString()
MessageString = "Total Sales: " & grandTotalDecimal.ToString("C")
'Display the message box
MessageBox.Show(MessageString, "Items Purchased", MessageBoxButtons.OKCancel)
End If
End Sub
End Class
You need to iterate over the array of ItemPrices objects, like this:
Dim itempriceDecimalTotal As Decimal
Dim itemweightDecimalTotal As Decimal
For Each theItemPrices As ItemPrices In ItemPricesArray
itempriceDecimalTotal += theItemPrices.itempriceDecimal
itemweightDecimalTotal += theItemPrices.itemweightDecimal
Next
Now you can convert the values to strings, like this:
Dim MessageString As String
Dim totalString As String
Dim numberOfItemsString As String
Dim weightOfItemsString As String
numberOfItemsString = totalItemsInteger.ToString()
totalString = itempriceDecimalTotal.ToString("C")
weightOfItemsString = itemweightDecimalTotal.ToString("N")
Finally, you can display the total values in a message box, like this:
MessageString = "Total Items : " & numberOfItemsString &
Environment.NewLine & "Total Weight: " & weightOfItemsString &
Environment.NewLine & "Subtotal: " & totalString
'Display the message box
MessageBox.Show(MessageString, "Items Purchased", MessageBoxButtons.OKCancel)
Getting the total of any property of the items in the array is a simple matter of leveraging the LINQ extension method Sum:
Dim grandtotal As Double = ItemPricesArray.Sum(Function(x) x.itempriceDecimal)
Then displaying as a string works well with the ToString() method:
Textbox1.Text = grandtotal.ToString("C2")'display as currency with 2 decimal places
Dim priceTotal As Double = (From itemPrice in ItemPricesArray
Select itemPrice.itempriceDecimal).Sum
Dim weightTotal As Double = (From itemPrice in ItemPricesArray
Select itemPrice.itemweightDecimal).Sum