How to create an error message box for an empty text box: VB 2010 Express
I am taking VB this semester, and while it is not required for this
particular assignment, I am curious how I can create a MessageBox error if
a text box is left empty.
We just covered using the Try/Catch statement, and I have successfully
created MessageBoxes for text boxes whose text is only numeric. For
example, a user must enter a name, and two numeric amounts. I am trying to
create an error if the Name text box is left empty, stop the program from
calculating the two amounts and return the insertion point to the Name
text box.
Is there an easier way to do this? The If/Then statement I currently have
does not stop the program from calculating (I am just starting out so go
easy on me):
Private Sub CalculateButton_Click(sender As System.Object, e As
System.EventArgs) Handles CalculateButton.Click
'Declare Variables
Dim SellingPrice, CostValue, Commission As Decimal
'Test to see if a name was provided the NameTextBox
If NameTextBox.Text = "" Then
MessageBox.Show("Please enter a Salesperson's name", "No entry",
MessageBoxButtons.OK, MessageBoxIcon.Error)
With NameTextBox
.Focus()
.SelectAll()
End With
End If
'Test if Numerical data was entered for SellingPriceTextBox
Try
'Convert Selling Price
SellingPrice = Decimal.Parse(SellingPriceTextBox.Text)
'Test if Numerical data was entered for CostValueTextBox
Try
'Convert Cost Value
CostValue = Decimal.Parse(CostValueTextBox.Text)
'Calculate the Commission earned
Commission = Decimal.Round(COMMISSION_RATE * (SellingPrice
- CostValue), 2)
'Format and display results
TotalCommissionLabel.Text = Commission.ToString("C")
Catch CostValueException As FormatException
'Handle a Cost Value exception
MessageBox.Show("Value must be a numeric value.", "Invalid
Input",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
With CostValueTextBox
.Focus()
.SelectAll()
End With
End Try
Catch SellingPriceException As FormatException
'Handle a Selling Price exception
MessageBox.Show("Price must be a numeric value.", "Invalid
Input",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
With SellingPriceTextBox
.Focus()
.SelectAll()
End With
End Try
End Sub
No comments:
Post a Comment