This program is supposed to read in values from a text file and get a sum of all these values. It is then to use information gathered from a series of check boxes and text boxes to calculate the final profit.
As the code is written now, the profit is only correct if all check boxes are selected, but I need it to be correct if one, two, or all three are checked. Here is the current code
Option Strict On
Imports System.IO
Public Class Form1
Dim sum As Double
Dim fileRead As Boolean
Dim profit As Double
Private Sub menOpen_Click(sender As Object, e As EventArgs) Handles menOpen.Click
Dim ofd As New OpenFileDialog
ofd.Filter = "text files |*.txt|All Files|*.*"
ofd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)
If ofd.ShowDialog() = Windows.Forms.DialogResult.OK Then
Dim selectedFileName As String = System.IO.Path.GetFileName(ofd.FileName)
If selectedFileName.ToLower = "profit.txt" Then
Dim line As String
Using reader As New StreamReader(ofd.OpenFile)
While Not reader.EndOfStream
line = reader.ReadLine
Dim value As Integer
If Integer.TryParse(line, value) Then
sum = sum + value
fileRead = True
End If
Console.WriteLine(line)
End While
End Using
Else
MessageBox.Show("You cannot use that file!")
End If
End If
End Sub
Private Sub menExit_Click(sender As Object, e As EventArgs) Handles menExit.Click
Me.Close()
End Sub
Private Sub radSales_CheckedChanged(sender As Object, e As EventArgs) Handles radSales.CheckedChanged
If radSales.Checked Then
profit = sum
End If
End Sub
Private Sub radSandO_CheckedChanged(sender As Object, e As EventArgs) Handles radSandO.CheckedChanged
If radSandO.Checked Then
If Trim(txtWages.Text) = "" Then
txtWages.Text = CStr(0)
End If
profit = (sum - CDbl(txtWages.Text) - CDbl(txtRent.Text) - CDbl(txtUtilities.Text))
End If
End Sub
Private Sub menComputeProfit_Click(sender As Object, e As EventArgs) Handles menComputeProfit.Click
If fileRead = False Then
MessageBox.Show("The file profit.txt has not been read in yet, the profit will be set to zero.")
sum = 0
End If
If chkWages.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtWages.Text) + Val(txtRent.Text) + Val(txtUtilities.Text))))
End If
If chkRent.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtRent.Text) + Val(txtWages.Text) + Val(txtUtilities.Text))))
End If
If chkUtilities.Checked Then
profit = CDbl(("$" & Val(sum) - (Val(txtUtilities.Text) + Val(txtWages.Text) + Val(txtRent.Text))))
End If
txtAnswer.Text = profit.ToString
End Sub
End Class
Any help would be greatly appreciated.
One of those text inputs is most likely empty (as the error states). Even if it wasn't empty, it could still be an invalid Double value.
In order to safely check if the string can be converted to a double, you can use Double.TryParse, like this:
If Double.TryParse(value, number) Then
Console.WriteLine("'{0}' --> {1}", value, number)
Else
Console.WriteLine("Unable to parse '{0}'.", value)
End If
Before you convert a string to double, check that the string is not empty. This is what error says. Afterwards you should check that the string in the box is actually numeric.
You are using TextChanged Event for txtAnswer
Private Sub txtAnswer_TextChanged(sender As Object, e As EventArgs) Handles txtAnswer.TextChanged
txtAnswer.Text = CStr(profit)
End Sub
So the above code is going to fire itself each time it changes! Just pop profit into txt Answer each time it is calculated
If chkWages.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtWages.Text)))
txtAnswer.text = profit
End If
If chkRent.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtRent.Text)))
txtAnswer.text = profit
End If
If chkUtilities.Checked Then
profit = CDbl(("$" & Val(sum) - Val(txtUtilities.Text)))
txtAnswer.text = profit
End If
A bit untidy but that should do it... you will need to do this whenever profit changed. And get rid of the TextChanged event.
UPDATED ANSWER FOR CLARITY
Ok I never add currency symbols so I'm not sure what CDbl(("$" & Val(Sum) - Val(txtWages.Text))) will do as it may treat it as a string character "$" rather than a currency.
Get rid of the "$" and just add the values... if you want to then stick the $ in front once calculation is complete say txtAnswer = $ & profit.toString
Related
sorry I'm a newbie and I'm trying to write a program to get ten integers from user with a an Inputbox or Textbox and displays the biggest and lowest one in a label with visual basic. I'll be appreciated if you help me out with this.
Thank you. this is my solution. I don't know how to compare these ten numbers with each other.
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers
Max = 0
i = 1
While (i <= 10)
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers
i = i + 1
End While
lblresult.Text = Container
End Sub
conceptually speaking you should use a List(Of Integer) or List(Of Double), perform the loop 10 times adding the value into the list.
Suppose this is our list
Dim container As New List(Of Integer)
To get input
Dim userInput = ""
Dim input As Integer
userInput = InputBox("please enter a number", "Enter a number")
If Integer.TryParse(userInput, input) Then
container.Add(input)
End If
After the loop
Console.WriteLine($"Min: {container.Min()} Max: {container.Max()}")
Does this make sense to you ?
Edit, based on asking for Windows Forms example.
You could do the following instead of a InputBox, requires a label, a button and a TextBox.
Public Class MainForm
Private container As New List(Of Integer)
Private Sub CurrentInputTextBox_KeyPress(sender As Object, e As KeyPressEventArgs) _
Handles CurrentInputTextBox.KeyPress
If Asc(e.KeyChar) <> 8 Then
If Asc(e.KeyChar) < 48 Or Asc(e.KeyChar) > 57 Then
e.Handled = True
End If
End If
End Sub
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
CurrentLabel.Text = "Enter number 1"
End Sub
Private Sub ContinueButton_Click(sender As Object, e As EventArgs) _
Handles ContinueButton.Click
If Not String.IsNullOrWhiteSpace(CurrentInputTextBox.Text) Then
container.Add(CInt(CurrentInputTextBox.Text))
CurrentLabel.Text = $"Enter number {container.Count + 1}"
If container.Count = 10 Then
ContinueButton.Enabled = False
CurrentLabel.Text =
$"Count: {container.Count} " &
$"Max: {container.Max()} " &
$"Min: {container.Min()}"
Else
ActiveControl = CurrentInputTextBox
CurrentInputTextBox.Text = ""
End If
End If
End Sub
End Class
I really didn't want to do your homework for you but I was afraid you might be hopelesly confused.
First let's go over your code. See comments
Private Sub btnShow_Click(sender As Object, e As EventArgs) Handles btnShow.Click
Dim i, Container, Max, Numbers 'Don't declare variables without an As clause
Max = 0 'Max is an object
i = 1 'i is and object
While i <= 10 'the parenthesis are unnecessary. You can't use <= 2 with an object
Numbers = InputBox("please enter a number", "Enter a number")
Max = Numbers
Container = Container & " " & Numbers 'Container is an object; you can't use & with an object
i = i + 1 'Again with the object i can't use +
End While
lblresult.Text = Container
End Sub
Now my approach.
I created a List(Of T) at the Form level so it can be seen from different procedures. The T stands for type. I could be a built in type or type you create by creating a Class.
The first click event fills the list with the inputted numbers. I used .TryParse to test if the input is a correct value. The first parameter is a string; the input from the user. The second parameter is a variable to hold the converted string. .TryParse is very clever. It returns True or False base on whether the input string can be converted to the correct type and it fills the second parameter with the converted value.
The second click event loops through the list building a string to display in Label1. Then we use methods available to List(Of T) to get the numbers you desire.
Private NumbersList As New List(Of Integer)
Private Sub FillNumberList_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim i As Integer
While i < 10
Dim input = InputBox("Please enter a whole number")
Dim inputInt As Integer
If Integer.TryParse(input, inputInt) Then
NumbersList.Add(inputInt)
i += 1 'We only increment i if the parse is succesful
End If
End While
MessageBox.Show("Finished Input")
End Sub
Private Sub DisplayResults_Click(sender As Object, e As EventArgs) Handles Button2.Click
Label1.Text = "You input these numbers "
For Each num In NumbersList
Label1.Text &= $"{num}, "
Next
Label2.Text = $"The largest number is {NumbersList.Max}"
Label3.Text = $"The smallest number is {NumbersList.Min}"
End Sub
I have been struggling with this code for a while. I'm trying to make it so after the user gets the number right, the program counts how many tries it has taken them to get the number right. How can I do this?
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
'SELECTS THE SECTET NUMBER
Randomize() 'WITHOUT rANDOMIZE, THE SAME SEQUENCE OF NUMBERS APPEARS EACH RUN
secretNumber = Int(Rnd(1) * 1000 + 1) 'picks a random nubmer between 1 and 1000
'sets the initial prompts
Me.lblLow.Text = 1
Me.lblHigh.Text = 1000
Me.txtGuess.Focus()
Dim count As Integer
btnEnterGuess.Enabled = True
btnStart.Enabled = False
Dim i As Integer
For i = 1 To count
count = count + 1
Next i
Do
count = count + 1
Loop Until count = secretNumber
MessageBox.Show("It took you " & i - 1 & " tries to get the number correct.")
End Sub
I threw this piece of code togeather, hopefully it will help.
Something to note when writing this kinda code, is that all this code is running on a single thread (unless you declare it otherwise). This means your program will become unresponsive when you run that for loop.
Public Class Form1
Dim count As Integer = 0
Dim answer As Integer = 0
Dim GameRunning As Boolean = True
Protected Overrides Function ProcessCmdKey(ByRef msg As System.Windows.Forms.Message,
ByVal keyData As System.Windows.Forms.Keys) _
As Boolean
'Gets all keystrokes on the fourm
If GameRunning Then
'converts keystroke to key ID and tests to see if the keystroke is the ENTER key
If msg.WParam.ToInt32() = CInt(Keys.Enter) Then
'try catch to prevent crash if text in entered
Try
If txtAnswer.Text = answer Then
MessageBox.Show("Congratz! It took you " & count & " tries to guess the number!")
Else
txtAnswer.Text = ""
count = (count + 1)
End If
Catch ex As Exception
End Try
End If
End If
'update label to show tries
lblTries.Text = "Tries: " & count
Return MyBase.ProcessCmdKey(msg, keyData)
End Function
Private Sub SetupOnLoad() Handles MyBase.Load
Reset()
End Sub
Public Sub Reset()
count = 0
Randomize()
answer = Int(Rnd(1) * 1000 + 1)
txtAnswer.Text = ""
lblTries.Text = "Tries: " & count
GameRunning = True
End Sub
'the Reset() code is ran on the program launch and when you press the button to prepare the game.
Private Sub Reset_Game() Handles BtnReset.Click
Reset()
End Sub
End Class
This code gets the user input in the text box. When the user presses ENTER, the program tests to see if its the correct number.
Hope this helped!
I will try something like this, randomize need to be placed outside of the click
Public Class Form1
Dim count As Integer = 0
Dim answer As Integer = 0
Private Sub btnStart_ClicK(sender As Object, e As EventArgs) Handles btnStart.Click
Randomize()
answer = Int(Rnd(1) * 1000 + 1)
btnStart.Enabled = False
btnGuess.Enabled = True
End Sub
Private Sub btnGuess_Click(sender As Object, e As EventArgs) Handles btnGuess.Click
count += 1
If answer = TextBox1.Text Then
MessageBox.Show("It took you " & count & " tries to get the number correct.")
btnStart.Enabled = True
btnGuess.Enabled = False
count = 0
answer = 0
Else
TextBox1.Text = ""
End If
End Sub
End Class
I have the simplest of if statements to work out if a person has passed an exam or not when I run the code the result always comes up as fail.
Public Class Form1
Dim EnglishMark As Single
Dim ScienceMark As Single
Dim MathsMark As Single
Dim AverageMark As Single
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
EnglishMark = Val(txtEnglish.Text)
ScienceMark = Val(txtScience.Text)
MathsMark = Val(txtMaths.Text)
AverageMark = (EnglishMark + ScienceMark + MathsMark) / 3 / 100
If (AverageMark >= 50) Then
lblDisplay.Text = "You Passed Well Done" & Format(AverageMark, "Percent")
Else
lblDisplay.Text = "You Failed Try Again" & Format(AverageMark, "Percent")
End If
End Sub
End Class
Thanks
I was wondering if you could help me? My question is that, is there a way of changing the value in my.Settings in a form if you enter a number/decimal in a textbox and click a button and then update in the settings to be then changed in another from which is linked to my.Settings in a variable?!
Form 1:
Public Class frmConverter
Dim input As String
Dim result As Decimal
Dim EUR_Rate As Decimal = My.Settings.EUR_Rates
Dim USD_Rate As Decimal = 1.6
Dim JYP_Rate As Decimal = 179.65
Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click
input = txtInput.Text
Try
If ComboBox1.Text = "£" Then
Pounds()
ElseIf ComboBox1.Text = "€" Then
Euros()
ElseIf ComboBox1.Text = "$" Then
Dollars()
ElseIf ComboBox1.Text = "¥" Then
Yen()
End If
Catch es As Exception
MsgBox("Error!")
End Try
End Sub
Private Sub btnSettings_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSettings.Click
Me.Hide()
frmExchange.Show()
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnReset.Click
txtInput.Text = ""
lblResult.Text = ""
End Sub
Function Pounds()
If ComboBox1.Text = "£" And ComboBox2.Text = "€" Then
result = (input * EUR_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
ElseIf ComboBox1.Text = "£" And ComboBox2.Text = "$" Then
result = (input * USD_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
ElseIf ComboBox1.Text = "£" And ComboBox2.Text = "¥" Then
result = (input * JYP_Rate)
lblResult.Text = FormatNumber(result, 2) & " " & ComboBox2.Text
End If
Return 0
End Function
Form 2:
Public Class frmExchange
Private Sub frmExchange_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
My.Settings.EUR_Rates = (txtinput.Text)
My.Settings.Save()
My.Settings.Reload()
End Sub
Public Sub SetNewRate(ByVal rate As Decimal)
txtinput.Text = rate.ToString
End Sub
Private Sub btnchange_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnchange.Click
If ComboBox1.Text = "€" Then
My.Settings.USD_Rates = (txtinput.Text)
frmConverter.SetNewRate(txtinput.Text)
End If
End Sub
End class
It sounds like you are trying to use My.Settings as some sort of set of global reference variables. Thats not what they are for, not how they work and not what they are.
First, turn on Option Strict as it looks like it may be Off. This will store the decimal value of a textbox to a Settings variable which is defined as a Decimal:
My.Settings.USD_Rates = CDec(SomeTextBox.Text)
Thats all it will do. It wont save the value and it wont pass it around or share it with other forms and variables.
My.Settings.Save 'saves current settings to disk for next time
My.Settings.Reload 'Load settings from last time
This is all covered on MSDN. There is no linkage anywhere. If you have code in another form like this:
txtRate.Text = My.Settings.USD_Rates.ToString
txtRate will not automatically update when you post a new value to Settings. There are just values not Objects (see Value Types and Reference Types). To pass the new value to another form:
' in other form:
Public Sub SetNewRate(rate As Decimal)
' use the new value:
soemTextBox.Text = rate.ToString
End Sub
in form which gets the change:
Private Sub btnchangeRate(....
' save to settings which has nothing to do with passing the data
My.Settings.USD_Rates = CDec(RateTextBox.Text)
otherForm.SetNewRate(CDec(RateTextBox.Text))
End Sub
You may run into problems if you are using the default form instance, but that is a different problem.
You botched the instructions. The 2 procedures are supposed to go in 2 different forms - one to SEND the new value, one to RECEIVE the new value. With the edit and more complete picture, there is an easier way.
Private Sub btnSettings_Click(...) Handles btnSettings.Click
' rather than EMULATE a dialog, lets DO a dialog:
'Me.Hide()
'frmExchange.Show()
Using frm As New frmExchange ' the proper way to use a form
frm.ShowDialog
' Im guessing 'result' is the xchg rate var
result = CDec(frm.txtInput.Text)
End Using ' dispose of form, release resources
End Sub
In the other form
Private Sub btnchange_Click(....)
' do the normal stuff with Settings, if needed then:
Me.Hide
End Sub
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