How to make an inputbox and text file appear in Visual Basic? - vb.net

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)

Related

I am working on vb.net and basic thing which I am doing is Deposit and withdraw of amounts

So If txtFirstName.Text = String.Empty And
txtLastName.Text = String.Empty And
txtAmount.Text = String.Empty Then
MsgBox("Please enter Information")
this part doesnt work at all, when i tried keeping the breakpoint and look at how it is working, It came out true but the msgbox was never shown.
and the deposit and withdraw functions work as strings.
Also I want to know How I can keep my code in different class and use it in this class for deposit and withdraw buttons.
Here is the code that I wrote:
Option Strict On
Option Explicit On
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
if not IsPostBack then
lblFirstName.Focus()
End Sub
Protected Sub btnConfirm_click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles btnConfirm.Click
If txtFirstName.Text = String.Empty And
txtLastName.Text = String.Empty And
txtAmount.Text = String.Empty Then
MsgBox("Please enter Information")
Else
doConfirm()
End If
End Sub
Private Sub doConfirm()
If rbtndeposit.Checked Then
txtBalance.Text += (txtAmount.Text)
ElseIf rbtnWithdraw.Checked Then
if txtAmount.text <= txtBalance.text then
txtBalance.text -= txtAmount.text
else
msgBox("Funds not sufficient")
End If
End If
End Sub
End Class
Firstly,Your logic with your text input is a bit flawed, the AND should be OrElse:
Protected Sub btnConfirm_click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConfirm.Click
If txtFirstName.Text.Length < 1 OrElse _
txtLastName.Text.Length < 1 OrElse _
txtAmount.Text.Length < 1 Then
MsgBox("Please enter Information")
Else
doConfirm()
End If
End Sub
Secondly, you are trying to do mathematical calculations with text values. Convert your input to the correct data type when doing calculations.
Private Sub doConfirm()
If rbtndeposit.Checked Then
txtBalance.Text = Cstr(Cdbl(txtBalance.Text) + Cdbl(txtAmount.Text))
ElseIf rbtnWithdraw.Checked Then
If CDbl(txtAmount.text) <= Cdbl(txtBalance.text) Then
txtBalance.text = Cstr(Cdbl(txtBalance.text) - Cdbl(txtAmount.text))
Else
msgBox("Funds not sufficient")
End If
End If
End Sub
You should how ever use tryparse to check if the input for the amount is valid or your code will crash when the input is not valid, for example:
Dim amount As Double
If Double.TryParse(txtAmount.text, amount) Then
If rbtndeposit.Checked Then
txtBalance.Text = Cstr(Cdbl(txtBalance.Text) + amount)
ElseIf rbtnWithdraw.Checked Then
If amount <= Cdbl(txtBalance.text) then
txtBalance.text = Cstr(Cdbl(txtBalance.text) - amount)
else
msgBox("Funds not sufficient")
End If
End If
Else
MessageBox.Show("Invalid amount entered.")
End if
As for storing your procedure is a separate class, I think just creating functions should be sufficient:
Private Sub Button1_WithDraw(sender As Object, e As EventArgs) Handles Button1_WithDraw.Click
txtBalance.Text = Withdraw(CDbl(txtAmount.Text), Cdbl(txtBalance.text)).ToString
End Sub
Private Function Withdraw(ByVal Amount As Double, ByVal Balance As Double) As Double
Balance = Balance - Amount
Return Balance
End Function

Why is it only displaying one result

This program is supposed to accept in valid candidates for voting, add the names typed in a text box to a list box. In the list box the user may double click on the candidate they choose. After the tally button is clicked a list box displaying the candidates' Names and votes will appear along side the other list box.
My problem is that the lstTallies only displays the last voted candidate.
Below is my code
Public Class Form1
Dim maxVotes As Integer
Dim winner As String
Dim votes() As Integer
Dim index As Integer
Dim candidates As String
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
If Not isValidInput(txtNewCandidate.Text) Then
Exit Sub
End If
lstCandidates.Items.Add(txtNewCandidate.Text)
txtNewCandidate.Clear()
txtNewCandidate.Focus()
ReDim Preserve votes(index)
index += 1
End Sub
Private Function isValidInput(ByRef firstName As String) As Boolean
If IsNumeric(txtNewCandidate.Text) Or txtNewCandidate.Text = "" Then
MsgBox("Please input a valid candidate name.")
txtNewCandidate.Focus()
Return False
Else
Return True
End If
End Function
Private Sub btnTally_Click(sender As Object, e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
lstTallies.Items.Add(lstCandidates.Text & " " & votes(lstCandidates.SelectedIndex))
End Sub
Private Sub lstCandidates_DoubleClick(sender As Object, e As EventArgs) Handles lstCandidates.DoubleClick
If lstCandidates.SelectedIndex = -1 Then
MsgBox("Select a candidate by double-clicking")
End If
votes(lstCandidates.SelectedIndex) += 1
MsgBox("Vote Tallied")
End Sub
End Class
Try this:
Assuming the index of the Candidate and his/her Vote are the same:
Private Sub btnTally_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnTally.Click
lstTallies.Visible = True
lblTally.Visible = True
For i = 0 To lstCandidates.Items.Count - 1
lstTallies.Items.Add(lstCandidates.Items(i).ToString & " - " & votes(i))
Next
End Sub
You cannot get the contents of the ListBox unless you iterate it.

Performing Calculations with Modules in Visual Basic

I am writing a program for my Visual Basic class that is supposed to be able to calculate the final total price for items selected from one list box and added to another. 2 of the items have sales tax that must be added into the final price. The program also has a Module that is supposed to be used to keep record of all taxes and is used to do all tax-related functions.
Here is the most current code.
Option Strict On
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
If (txtQuantity.Text = "") Then
MessageBox.Show("Please enter a quantity for the item you selected")
ElseIf Not Integer.TryParse(txtQuantity.Text, CInt(txtQuantity.Text)) Then
MessageBox.Show("The quantity entered is not numeric. Please add a numeric quantity.")
Exit Sub
Else
lstPurchased.Items.Add(txtQuantity.Text & " " & lstSale.Text)
End If
End Sub
Private Sub btnCalculate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCalculate.Click
Dim int As Integer
Dim total As Double = 0
For i As Integer = 0 To lstPurchased.Items.Count - 1
Dim lst() As String = lstPurchased.Items(i).ToString.Split({CChar(" ")}, 2)
Integer.TryParse(lst(0), int)
total += TaxesModule.SalesTax(int, lst(1))
Next
MessageBox.Show(CStr(FormatCurrency(total)))
End Sub
Private Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClear.Click
lstPurchased.Items.Clear()
txtQuantity.Clear()
End Sub
End Class
And the most recent code for the module
Option Strict On
Module TaxesModule
Private Const DONUT_TAX As Decimal = CDec(0.083)
Private Const RAISIN_TAX As Decimal = CDec(0.02)
Private Const SS_TAX As Decimal = CDec(0.062) ' <-- you are not using this
Public Function SalesTax(ByVal Quantity As Integer, ByVal item As String) As Double
Dim TotalWithSalesTax As Double
If item = "Wheat Bread" Then
TotalWithSalesTax += (Quantity * 1.15)
ElseIf item = "White Bread" Then
TotalWithSalesTax += (Quantity * 1.05)
ElseIf item = "Donuts" Then
TotalWithSalesTax += (Quantity * (0.5 * DONUT_TAX) + (Quantity * 0.5))
ElseIf item = "Raisins" Then
TotalWithSalesTax += (Quantity * (0.25 * RAISIN_TAX) + (Quantity * 0.25))
End If
Return TotalWithSalesTax
End Function
End Module
As the code is written now, the only problem I'm having is that the TotalWithSalesTax for "Raisins" is not calculating correctly. For example, if I select "Raisins" from the list box and add it with a quantity of 1 to the other list box, the total that is displayed in the message box is $0.00.
I'm starting to think the issue is with the following section of code:
For i As Integer = 0 To lstPurchased.Items.Count - 1
Dim lst() As String = lstPurchased.Items(i).ToString.Split({CChar(" ")}, 2)
Because I have tried making changes such as
For i As Integer = 1 ...
And that caused both Donuts and Raisins to give me a total of $0.00 in the message box. So I'm wondering if maybe how the count is set up is not allowing it to go through the entire list, but I don't know how to fix that?
I'm still really new to Visual Basic, and programming in general really and this is my first time working with modules. Can anybody help me figure out what I'm doing wrong, so I can move onto other parts of the program?
I have modified your code, hope this is what you want. Added comment in the code. Note i have removed all Public variables.
Public Class Form1
Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd.Click
If (txtQuantity.Text = "") Then
MessageBox.Show("Please enter a quantity for the item you selected")
ElseIf Not Integer.TryParse(txtQuantity.Text, txtQuantity.Text) Then
MessageBox.Show("The quantity entered is not numeric. Please add a numeric quantity.")
Exit Sub
Else
lstPurchased.Items.Add(txtQuantity.Text & " " & lstSale.Text)
End If
End Sub
Private Sub btnCalculate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnCalculate.Click
Dim int As Integer
Dim total As Double = 0
'you have to loop through the list to calculate the total
' hope this is what you want
For i As Integer = 0 To lstPurchased.Items.Count - 1
' We split the list item into the quantity and the item name
Dim lst() As String = lstPurchased.Items(i).ToString.Split({CChar(" ")}, 2)
'lst(1) contains the item name
Integer.TryParse(lst(0), int)
total += TaxesModule.SalesTax(int, lst(1))
Next
MessageBox.Show(CStr(FormatCurrency(total)))
End Sub
Private Sub btnClear_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnClear.Click
lstPurchased.Items.Clear()
txtQuantity.Clear()
End Sub
End Class
The module
Module TaxesModule
Private Const DONUT_TAX As Decimal = CDec(0.083)
Private Const RAISIN_TAX As Decimal = CDec(0.02)
Private Const SS_TAX As Decimal = CDec(0.062) ' <-- you are not using this
Public Function SalesTax(ByVal Quantity As Integer, ByVal item As String) As Double
Dim TotalWithSalesTax As Double
If item = "Wheat Bread" Then
TotalWithSalesTax = (Quantity * 1.15)
ElseIf item = "White Bread" Then
TotalWithSalesTax = (Quantity * 1.05)
ElseIf item = "Donuts" Then
TotalWithSalesTax = (Quantity * (0.5 * DONUT_TAX) + (Quantity * 0.5))
ElseIf item = "Raisins" Then
TotalWithSalesTax = (Quantity * (0.25 * RAISIN_TAX) + (Quantity * 0.25))
End If
Return TotalWithSalesTax
End Function
End Module

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))

Random Numbers to Text in Label

Public Class MainForm
Private Sub exitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles exitButton.Click
Me.Close()
End Sub
Private Sub guestsTextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles guestsTextBox.KeyPress
' allows only numbers and the Backspace key
If (e.KeyChar < "0" OrElse e.KeyChar > "9") AndAlso
e.KeyChar <> ControlChars.Back Then
e.Handled = True
End If
End Sub
Private Sub MainForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'fills the list box and selects the first item
typeListBox.Items.Add("Kid's Birthday")
typeListBox.Items.Add("21st Birthday")
typeListBox.Items.Add("40th Birthday")
typeListBox.Items.Add("Other Birthday")
typeListBox.SelectedIndex = 0
End Sub
Private Sub calcButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles calcButton.Click
'displays the total charge
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Integer.TryParse(guestsTextBox.Text, guests)
typeIndex = typeListBox.SelectedIndex
'determine the price per guest
Select Case typeIndex
Case 0 'Kid's Birthday
guestPrice = 11
Case 1 '21st Birthday
guestPrice = 20
Case 2 '40th Birthday
guestPrice = 25
Case Else 'other birthdays
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
totalLabel.Text = totalCharge.ToString("C0")
End Sub
Private Sub testDataButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles testDataButton.Click
Dim guests As Integer
Dim typeIndex As Integer
Dim guestPrice As Integer
Dim totalCharge As Integer
Dim randomGen As New Random
Dim setCounter As Integer = 1
testDataLabel.Text = String.Empty
Do
guests = randomGen.Next(1, 51)
typeIndex = randomGen.Next(0, 4)
For Each I As Object In typeListBox.SelectedItems
testDataLabel.Text += I.ToString() & ControlChars.NewLine
Next
'determine the price per guest
Select Case typeListBox.SelectedIndex
Case 0
guestPrice = 11
Case 1
guestPrice = 20
Case 2
guestPrice = 25
Case Else
guestPrice = 15
End Select
'calculate and display the total charge
totalCharge = guests * guestPrice
testDataLabel.Text = testDataLabel.Text &
typeIndex.ToString & " " &
guests.ToString & " " &
totalCharge.ToString("C0") &
ControlChars.NewLine
setCounter += 1
Loop Until setCounter > 10
End Sub
Private Sub typeListBox_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles typeListBox.SelectedIndexChanged
End Sub
End Class
When I click on a button named "Generate Test Data" It generates a list of random numbers in a label. I want these numbers to say the type of birthday instead of the number.
0 being "Kid's Birthday"
1 being "21st Birthday"
2 being "40th Birthday"
and 3 being "Other Birthday"
How would I go about doing this?
Any help would be much appreciated!
If I understood your question correctly, you can declare an enum and have a dictionary of that enum to String.
The Enum takes care of dealing with numbers in code, and rather use human readable constructs. Dictionary will make sure your users will also see human readable constructs.
Please see below code (needs a brand new WinForms project and a ListBox called ListBox1 on the main form):
Option Strict On
Public Class Form1
'Declare this enum to avoid dealing with naked numbers in code
Enum BirthdayTypes
btKids = 0
bt21st = 1
bt40th = 2
btOther = 3
End Enum
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) _
Handles MyBase.Load
'Suppose your input value is a number,
'but you don't want to deal with numbers
Dim typeIndex As Integer = 2
'You can convert your number to BirthdayTypes,
'making your input "correct"
Dim typeIndexBt As BirthdayTypes = ConvertBirthdayIndexToType(typeIndex)
'Calculation of guest price is now "human readable"
Dim guestPrice As Integer = CalculateGuestPrice(typeIndexBt)
'You can create a dictionary for diplaying the values
Dim displayDictionary As New Dictionary(Of BirthdayTypes, String)
With displayDictionary
.Add(BirthdayTypes.btKids, "Kid's Birthday")
.Add(BirthdayTypes.bt21st, "21st Birthday")
.Add(BirthdayTypes.bt40th, "40th Birthday")
.Add(BirthdayTypes.btOther, "Other Birthday")
End With
'Here is how you would those values into a ListBox
With ListBox1
.DataSource = displayDictionary.ToList
.ValueMember = "Key"
.DisplayMember = "Value"
End With
'Now your ListBox displays strings,
'but SelectedValue would return an object of type BirthdayTypes
'You can extract random values from the above dictionary by index,
'and create a new list from it
Debug.WriteLine(ListBox1.SelectedValue) 'outputs btKids
End Sub
Private Function CalculateGuestPrice(bt As BirthdayTypes) As Integer
Select Case bt
Case BirthdayTypes.btKids : Return 11
Case BirthdayTypes.bt21st : Return 20
Case BirthdayTypes.bt40th : Return 25
Case BirthdayTypes.btOther : Return 15
End Select
'should never here
Throw New Exception("Unknown birthday type")
End Function
Private Function ConvertBirthdayIndexToType(index As Integer) As BirthdayTypes
If index < 3 Then Return CType(index, BirthdayTypes)
Return BirthdayTypes.btOther
End Function
End Class
Disclaimer: this code is just a demo of what can be done, not meant to be used a complete solution.
I would use a string.
Dim thestring() As String = {"Kid's Birthday", _
"21st Birthday", _
"40th Birthday", _
"Other Birthday"}
Now each of those numbers will represent the text in thestring.
thestring(0) = kids birthday
thestring(1) = 21 birthday
thestring(2) = 40th birthday
thestring(3) = other birthday
Make sense? I would help further, but i don't quite get what you are trying to do.