I am currently going through a book on beginning VB,NET and am trying to complete one of the exercises in the book. I have created a function that validates user entries to check that they are numeric and within certain a range.
If text value is entered into the textbox I get an exception error saying that
"Cast from String to type double is not valid"
The main code is as follows:
The highlighted code is where the exception is thrown.Code:Private Sub btnCalculate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnCalculate.Click Dim dOrderTotal As Decimal Dim dDiscountPct As Decimal Dim dDiscountAmount As Decimal Dim dInvoiceTotal As Decimal If ValidEntry(txtOrderTotal.Text) = 0 Then dDiscountAmount = DiscAmount(dOrderTotal) dInvoiceTotal = dOrderTotal - dDiscountAmount lblDiscountAmount.Text = FormatNumber(dDiscountAmount) lblInvoiceTotal.Text = FormatNumber(dInvoiceTotal) ElseIf ValidEntry(txtOrderTotal.Text) = 1 Then ' Not IsNumeric MessageBox.Show("You must enter a numeric value.", "Entry error") ElseIf ValidEntry(txtOrderTotal.Text) = 2 Then ' Out of Range Value MessageBox.Show("Order total must be between 10 and 10000", "Entry error") End If txtOrderTotal.Focus() End Sub Module CalcModule Const dMinOrderTotal As Decimal = 10 Const dMaxOrderTotal As Decimal = 10000 Public Function DiscAmount(ByVal Ordertot As Decimal) As Decimal Dim dDiscount As Decimal, dDisAmount As Decimal If Ordertot >= 500 Then dDiscount = 0.2 ElseIf Ordertot >= 250 Then dDiscount = 0.15 ElseIf Ordertot >= 100 Then dDiscount = 0.1 Else ' < 100 dDiscount = 0 End If dDisAmount = dDiscount * Ordertot Return (dDisAmount) End Function Public Function ValidEntry(ByVal OrderTotal As String) As Integer Dim dValidType As Integer ' 0 = valid entry ' 1 = nonnumeric ' 2 = invalidrange If IsNumeric(OrderTotal) And OrderTotal >= dMinOrderTotal And OrderTotal <= dMaxOrderTotalIf IsNumeric(OrderTotal) And OrderTotal >= dMinOrderTotal And OrderTotal <= dMaxOrderTotal Then dValidType = 0 ElseIf IsNumeric(OrderTotal) And (OrderTotal < dMinOrderTotal Or OrderTotal > dMaxOrderTotal) Then dValidType = 2 Else dValidType = 1 End If Return dValidType End Function End Module
Any help to solve this would be appreciated.




Reply With Quote