I have a task to make a calculation of selling price and cost value.
I don't know have any idea to make a good coding for exception.
Private Sub ButtonCalculate_Click(sender As Object, e As EventArgs) Handles ButtonCalculate.Click
Dim SellingPrice As Double
Dim CostValue As Double
Dim Commission As Double
Dim CommissionRate As Double = 0.2
If Me.TextBoxSellingPrice.Text <> "" Or Me.TextBoxCostValue.Text <> "" Then
Try
SellingPrice = Double.Parse(TextBoxSellingPrice.Text)
CostValue = Double.Parse(TextBoxCostValue.Text)
'Calculation
Commission = CommissionRate * (SellingPrice - CostValue)
'Display
Me.TextBoxDisplay.Text = Me.TextBoxName.Text
Me.TextBoxCommission.Text = "RM" + Commission.ToString("F2")
Catch
MessageBox.Show("Wrong Input", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
Else
MessageBox.Show("Please fill your data completely", "Notice", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
Output:
Figure 1
Using exception handling to check that data is correct isn't really the best practice. For a start, the performance of Try..Catch blocks is pretty poor compared to just using If..Then..Endif as there is a fair amount of stuff happening in the background with exceptions. In your case it wont make a major difference, but if the Try..Catch..End Try is in a loop, your program can take quite a performance hit.
There is little else to do other than to write some If..End If statements to validate your input data .. As other commenters had stated, using .TryParse is an exellent way to start things off ..
If Not Double.TryParse(TextBoxSellingPrice.Text, SellingPrice) Or Not Double.TryParse(TextBoxCostValue.Text, CostValue) Then
MessageBox.Show("Invalid input. Please enter positive numbers only")
Exit Sub
End If
If SellingPrice < CostValue Then
MessageBox.Show("Selling Price must be greater than cost")
Exit Sub
End If
If Not SellingPrice > 0 Or Not CostValue > 0 Then
MessageBox.Show("Selling price and cost must be >0")
Exit Sub
End If
'Calculation
Commission = CommissionRate * (SellingPrice - CostValue)
'Display
Me.TextBoxDisplay.Text = Me.TextBoxName.Text
Me.TextBoxCommission.Text = "RM" + Commission.ToString("F2")
You could also have a look at the ErrorProvider component
Related
I am working on an assignment for school where I have to validate a data entry. My first issue is that running the function does not produce an error message when I run the code and use any other letter as customer type.
My second issue is that the 40% discount for the Else clause that is commented out is applying even though it is commented out.
Private Sub GetDiscountPercent(customerType As String, subtotal As Decimal,
ByRef discountPercent As Decimal)
If customerType = "R" Then
If subtotal < 100 Then
discountPercent = 0
ElseIf subtotal >= 100 AndAlso subtotal < 250 Then
discountPercent = 0.1D
ElseIf subtotal >= 250 Then
discountPercent = 0.25D
End If
ElseIf customerType = "C" Then
If subtotal < 250 Then
discountPercent = 0.2D
Else
discountPercent = 0.3D
End If
'Else
'discountPercent = 0.4D
End If
End Sub
Private Sub btnExit_Click(sender As Object,
e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub ClearResultBoxes(sender As Object,
e As EventArgs) _
Handles txtCustomerType.TextChanged, txtSubtotal.TextChanged
txtDiscountPercent.Text = ""
txtDiscountAmount.Text = ""
txtTotal.Text = ""
End Sub
Function IsValidCustomerType() _
As Boolean
If IsValidCustomerType = "R" Then
MessageBox.Show("Customer Type has to be R or C or T", "Entry Error")
txtCustomerType.Select()
Return False
Else
Return True
End If
If Not IsValidCustomerType = "C" Then
MessageBox.Show("Customer Type has to be R or C or T", "Entry Error")
txtCustomerType.Select()
Return False
Else
Return True
End If
End Function
End Class
I am working on an assignment for school where I have to validate a data entry. My first issue is that running the function does not produce an error message when I run the code and use any other letter as customer type.
Speculating that this is wrong:
Function IsValidCustomerType() _
As Boolean
If IsValidCustomerType = "R" Then
^^^^^^^^^^^^^^^^^^^^^^^^^
MessageBox.Show("Customer Type has to be R or C or T", "Entry Error")
txtCustomerType.Select()
Return False
Else
Return True
End If
If Not IsValidCustomerType = "C" Then
MessageBox.Show("Customer Type has to be R or C or T", "Entry Error")
txtCustomerType.Select()
Return False
Else
Return True
End If
End Function
End Class
You've declared that this function returns a boolean. You cannot compare this to a string in a meaningful way, and if option strict is on it won't even compile.
Even if you could compare a bool with a string the logic of this is wrong. If you managed to make Type = C, then the code will never reach that check because it either returns true or false (in this case false) because C is not R, so while C is valid, you'll never check for it being C, because the code will only ever consider if it's R or not
You need to stop coding and write out your algorithm using pen and paper
My second issue is that the 40% discount for the Else clause that is commented out is applying even though it is commented out.
Gonna go out on a limb here and say that because this code is wrong, or because of some other compiler error elsewhere, you're seeing a dialog that says "There were build errors. Whould you like to run the last successful build?" and youre saying "Yes", and you're running a version of the app where that code isn't commented out..
If user inputs something else than an integer, program will not proceed but will give a message box telling there is an error.
Here is what I have now and it's not working:
Sub Validation0()
If IsNumeric(curBat) Then
' Here, it still could be an integer or a floating point number
If CLng(curBat) = curBat Then
Else
MessageBox.Show("Please enter a number greater than 0.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
End If
End If
End Sub
Try to diversify your code
1) identify whether string is integer
2) then identify whether it is greater than 0
Sub Validation0()
If IsNumeric(curBat) Then
' Here, it still could be an integer or a floating point number
dim curBat2 as integer = Convert.ToInt32(curBat)
If curBat2 > 0 Then
Else
MessageBox.Show("Please enter a number greater than 0.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation,
MessageBoxDefaultButton.Button1)
End If
End If
End Sub
If you want to round off integer value then use
Math.Roundoff(curBat2)
I recently coded a program on VB.NET that shows Input1 Mod Input2 for example. Here i use function :
Private Function remainder(intno1 As Integer, intno2 As Integer) As Integer
Dim intresult As Integer
intresult = intno1 Mod intno2
remainder = intresult
End Function
Then i called it on Button_Click event :
Dim intm As Integer, intn As Integer
Dim intmod As Integer
intm = Val(TextBox1.Text)
intn = Val(TextBox2.Text)
If TextBox1.Text >= TextBox2.Text Then
MsgBox("Error while computing proccess ! Please try Again.", vbOKOnly + vbCritical, "Error!")
**Stop statement**
End If
intmod = remainder(intm, intn)
RichTextBox1.Text = "The result is " & Str(intmod)
as you can see on this code, i use if statements when txt1 is bigger or equals txt2 then message box shows. before End If clause i want to use statement that stop running the code. i mean stop doing those process on Function.
I use Stop and End statements but after i debug the program, it stop responding or even exit the program.
What should i do exactly here ?
You would use an Exit Sub call to stop executing that routine right there. If it had been a function, Exit Function
BTW, you should use CInt rather than Val to force to integer and your message should be more helpful (i.e., what was the error while computing?). Something along the lines of "First integer must be less than the second" would be more useful to a user.
Try one of these to exit a method
Exit Sub
Or
Return
Simple use :
Dim intm As Integer, intn As Integer
Dim intmod As Integer
intm = Val(TextBox1.Text)
intn = Val(TextBox2.Text)
If TextBox1.Text >= TextBox2.Text Then
MsgBox("Error while computing proccess ! Please try Again.", vbOKOnly + vbCritical, "Error!")
Exit Sub
End If
intmod = remainder(intm, intn)
RichTextBox1.Text = "The result is " & Str(intmod)
when you want exit from a function without return any value, It shows the software failure , and must not give the impression of 'business as usual' to the responsible caller code.
for this you need Throw an exception:
Throw New Exception("Error while computing proccess ! Please try Again.")
in this case the exception its not a suprise, it is likely command will be executed inadvertentlyexecuted inadvertently when the input text-boxes not correspond to expectations.
In this case there is no reason to throw an error, but has prevented the execute function already in the code caller, not in the function body.
I want my program to check whether the inputs in a TextBox meet certain condition. If the target condition is not met, the cursor should focus back on that particular TextBox.
My code:
Private Sub ButtonSubmit_Click(sender As Object, e As EventArgs) Handles ButtonSubmit.Click
EnterVotes.LabelCan1.Text = CandName1.Text
EnterVotes.Labelcan2.Text = CandName2.Text
EnterVotes.LabelCan3.Text = CandName3.Text
EnterVotes.LabelCan4.Text = CandName4.Text
EnterVotes.LabelCan5.Text = CandName5.Text
If CandName1.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 1")
End If
loading.Show()
Me.Hide()
If CandName1.Text = "" Then //Show your message here // CandName1.focus()//to return to that textbox Else //Show your
message here End If
use the method focus() to return and re-write into that textbox
It is actually quite simple
just check if the value of the text is > 1
then put focus on the textbox
heres an example
if txtbox.text.value < 1 then
messagebox.show("You must enter data for textbox")
txtbox.focus()
end if
and then continue method for each text box you are working with
Could get fancy and use some linq to go threw your names.
Dim Candidate() As TextBox
Candidate = Me.Controls.OfType(Of TextBox)().Where(Function(c) c.Name.Contains("CandName")).ToArray()
Dim i As Integer = 0
While i < Candidate.Count
If(Candidate(i).text.value < 1)
MessageBox.Show("Please enter a name in Candidate " & (i + 1).ToString())
Candidate(i).Focus()
Exit While
End If
i += 1
End While
This way you can check all your candidates in one shot. This is untested code, but I think it should work.
You can play around with this and edit however you please it's pretty flexible at this point.
I think this might be the way but not very efficient.
If CandName1.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 1")
CandName1.Focus()
Else
CandName2.Focus()
End If
If CandName2.Text = "" Then
MessageBox.Show("Please enter an name in Candidate 2")
CandName3.Focus()
Else
CandName3.Focus()
End If
If CandName3.Text = "" Then
MessageBox.Show("Please enter a name in Candidate 3")
CandName3.Focus()
Else
CandName4.Focus()
End If
If CandName4.Text = "" Then
MessageBox.Show("Please enter a name in candidate 4")
CandName4.Focus()
Else
CandName5.Focus()
End If
If CandName5.Text = "" Then
MessageBox.Show("Pleae enter a name in candidat 5")
CandName5.Focus()
Else
loading.Show()
End If
If String.IsNullOrWhitespace( CandName1.Text ) Then
MessageBox.Show("Please enter a name in Candidate 1")
CandName1.Focus()
Return
End If
... for all five
loading.Show()
Me.Hide()
You want to make sure to exit this early with the Return statements so you don't get to the code:
loading.Show()
Me.Hide()
I have started over and everything is working as intended except for 2 of the accumulating totals, the calculation is not working the way I need it to. Instead of adding previous sales to the total it tacks the new sale on the end...
for example: I input 1 Snowboard and 1 Snowboard with Boots, this works, 1 is shown in the summary for both Snowboards and Snowboards with Boots. However when I try to input again in order to keep a running total of sales I have a problem, I enter 1 Snowboard and 1 Snowboard with Boots, and the summaries show 11 rather than 2. Why does this happen?
' Declare module-level variables and constants.
Private SnowBoardsSold, BootsSold, SaleCount As Integer
Private ItemsSold As Integer
Private TotalSales As Decimal
Const SNOWBOARD_RATE As Decimal = 20D
Const BOOTS_RATE As Decimal = 30D
Private Sub CalculateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CalculateButton.Click
' Calculate the prices
Dim SnowBoards, Boots As Integer
Dim SnowBoardSale, BootsSale, ThisSale, AverageSalesEver As Decimal
Try
' Convert the Snowboard input to numeric variable.
SnowBoards = Integer.Parse(SnowboardsTextBox.Text)
Try
' Convert Boots if Snowboard was successful.
Boots = Integer.Parse(WithBootsTextBox.Text)
' Calculate values for sale.
SnowBoardSale = SnowBoards * SNOWBOARD_RATE
BootsSale = Boots * BOOTS_RATE
ThisSale = SnowBoardSale + BootsSale
' Calculate summary values.
TotalSales += ThisSale
BootsSold += BootsSale
SnowBoardsSold += SnowBoardSale
SaleCount += 1
AverageSalesEver = TotalSales / SaleCount
' Format and display prices for the sale.
SnowBoardsPriceTextBox.Text = SnowBoardSale.ToString("c")
BootsPriceTextBox.Text = BootsSale.ToString("c")
TotalPriceTextBox.Text = ThisSale.ToString("c")
' Format and display values for the summary.
SnowBoardRentalTextBox.Text += SnowBoards.ToString()
BootsRentalTextBox.Text += Boots.ToString()
TotalChargesTextBox.Text = TotalSales.ToString("c")
AverageChargeTextBox.Text = AverageSalesEver.ToString("c")
Catch BootsException As FormatException
' Handle a Boots exception.
MessageBox.Show("Please enter numbers.", "Data Entry Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With WithBootsTextBox
.Focus()
.SelectAll()
End With
End Try
Catch SnowBoardsException As FormatException
' Handle a SnowBoard exception.
MessageBox.Show("Please enter numbers.", "Data Entry Error",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With SnowboardsTextBox
.Focus()
.SelectAll()
End With
Catch AnException As Exception
'Handle any other exception.
MessageBox.Show("Error: " & AnException.Message)
End Try
End Sub
First, you might want to change the way you grab the numbers:
'Convert snowboard input value to numeric variable.
SnowboardInteger = Integer.Parse(SnowboardsTextBox.Text)
to:
Dim SnowboardInteger As Integer
If TryParse.Integer(SnowboardsTextBox.Text, SnowboardInteger) = False then
' if it parses, SnowboardInteger will have the value,
'else the function returns false
MessageBox.Show("Please enter numbers")
End if
Also, you are parsing the textboxes twice. Once in the declaration then right after. This doesnt look right:
SnowboardSaleCountInteger += 1
WithBootsSaleCountInteger += 1
TotalSaleCountInteger += TotalChargesSumInteger ' ?????
AverageChargeInteger = TotalChargesSumInteger / TotalSaleCountInteger
Adding 'charges' to a 'counter' doesnt seem right. If you want the avg shouldnt it be:
TotalSaleCountInteger = SnowboardSaleCountInteger + WithBootsSaleCountInteger
If you want fractions such as 'xx.yy' in the result, AverageChargeInteger should be a Double or Decimal, unless whole dollars are ok for the assignment.
If you need to accumulate from previous clicks, then you need to move some declarations out of the procedure up by SnowboardSumInteger, WithBootsSumInteger so they can accumulate. As it is, WithBootsSaleCountInteger, TotalSaleCountInteger dont do anything and are always 1. I wonder if as a 'SaleCounter' they shouldnt increase by the value in the textbox rather than just 1 (dont have the assignment in front of me).
One more thing you might need to do is here:
SnowboardPriceInteger = SnowboardInteger * SNOWBOARD_RENTAL_RATE
WithBootsPriceInteger = WithBootsInteger * WITH_BOOTS_RENTAL_RATE
TotalPriceInteger = SnowboardPriceInteger + WithBootsPriceInteger
Your constants are Decimal (SNOWBOARD_RENTAL_RATE) so, the result of the calc has to go into a Decimal var, but SnowboardPriceInteger and the other are not. An integer cannot store a fractional result from the multiplication or division.
something like:
' sales accumulators
Private TotalSales As Decimal = 0
Private ItemsSold As Integer = 0
Click Event:
' this sale:
Dim Snowboards As Integer
Dim Boots As Integer
' get the values from the text boxes, then:
Dim SnowBoardSale As Decimal = (SnowBoards * SnowBoardRate)
Dim BootsSale As Decimal = (Boots * BootsRate)
Dim ThisSale As Decimal = SnowBoardSale + BootsSale
' update accumulators
TotalSales += ThisSale
ItemsSold += (Boots + Snowboards)
' calc the average
Dim AverageSalesEver AS Decimal = TotalSales / ItemsSold
' Display results in textboxes
'(this exercise is left to the student ;) )
HTH
I think you just confused yourself with too many variables and ones left over from old attempts.