我这个学期正在学习 VB,虽然这个特定的作业不需要它,但我很好奇如果文本框为空,我如何创建 MessageBox 错误。
我们刚刚介绍了如何使用 Try/Catch 语句,并且我已经成功地为文本仅为数字的文本框创建了 MessageBoxes。例如,用户必须输入姓名和两个数字金额。如果名称文本框留空,我将尝试创建一个错误,停止程序计算这两个数量并将插入点返回到名称文本框。
有没有更简单的方法来做到这一点?我目前拥有的 If/Then 语句不会阻止程序计算(我刚刚开始,所以对我来说放轻松):
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