vb.net 如何为空文本框创建错误消息框:VB 2010 Express

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18862674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 17:10:07  来源:igfitidea点击:

How to create an error message box for an empty text box: VB 2010 Express

vb.net

提问by 27E_20

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.

这学期我正在学习 VB,虽然这个特定作业不需要它,但我很好奇如果文本框留空,我如何创建 MessageBox 错误。

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.

我们刚刚介绍了使用 Try/Catch 语句,并且我已经成功地为文本仅为数字的文本框创建了 MessageBoxes。例如,用户必须输入名称和两个数字金额。如果名称文本框留空,我试图创建一个错误,停止程序计算这两个数量并将插入点返回到名称文本框。

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

有没有更简单的方法来做到这一点?我目前拥有的 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

回答by ??ssa P?ngj?rdenlarp

    If NameTextBox.Text = "" Then
        MessageBox.Show("Please enter a Salesperson's name", "No entry",
                            MessageBoxButtons.OK, MessageBoxIcon.Error)
        With NameTextBox
            .Focus()
            .SelectAll()
        End With
        Exit Sub                    ' tell it to skip the rest
    End If

I'd split that part off into a Function to determine if the data is valid, and only invoke the Calculations if it is valid. Something like:

我将该部分拆分为一个函数以确定数据是否有效,并且仅在有效时才调用计算。就像是:

Private Sub CalculateButton_Click...
    If DataComplete() Then
        DoCalcs()
    End If

You are likely to want to perform those calcs elsewhere so it would be nice to be able to invoke them from other than a click event. DataCompletecould be as little as:

您可能希望在其他地方执行这些计算,因此能够从点击事件以外的地方调用它们会很好。 DataComplete可以少至:

Return NameTextBox.Text.Length > 0

Later it would likely need to see if such a sales person exists etc

稍后它可能需要查看是否存在这样的销售人员等

回答by Vernon Miner

You are almost there. Just a little massaging of your code should get it working.

你快到了。只需稍微按摩一下您的代码即可使其正常工作。

If NameTextBox.Text = "" Then
   MessageBox.Show(...)
Else
   Do Calculation...
End If

回答by Karl Anderson

One approach is to use If-Elselogic, like this:

一种方法是使用If-Else逻辑,如下所示:

Private Sub CalculateButton_Click(sender As System.Object, e As System.EventArgs) Handles CalculateButton.Click
    'Test to see if a name was provided the NameTextBox
    If String.IsNullOrEmpty(NameTextBox.Text) Then
        MessageBox.Show("Please enter a Salesperson's name", "No entry",
                            MessageBoxButtons.OK, MessageBoxIcon.Error)
        With NameTextBox
            .Focus()
            .SelectAll()
        End With
    Else
        'Declare Variables
        Dim SellingPrice, CostValue, Commission As Decimal

        '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 If
End Sub

This guarantees either the error message is shown to the user indicating that they need to enter a salesperson's name or the calculation logic is performed, but not both.

这保证要么向用户显示错误消息,指示他们需要输入销售人员的姓名,要么执行计算逻辑,但不能同时执行。

Note: I also added the use of the String.IsNullOrEmpty()method to test whether or not the textbox had a value. I find that syntax cleaner than checking for an empty string.

注意:我还添加了使用String.IsNullOrEmpty()方法来测试文本框是否有值。我发现这种语法比检查空字符串更清晰。

回答by user6177495

If lblPriceTotalClothes.Text & lblPriceTotalElectronics.Text & lblPriceTotalGames.Text & lblPriceTotalJewellry.Text = Nothing Then
        MessageBox.Show("Please choose something to buy!", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
        lblSubtotalPrice.Text = FormatCurrency(0)
        lblTotalCostPrice.Text = FormatCurrency(0)
        lbltaxesPrice.Text = FormatCurrency(0)
        Return
Else
        lblSubtotalPrice.Text = FormatCurrency(subTotalPrice)
        taxes = FormatCurrency(subTotalPrice * 0.13)
        lblTotalCostPrice.Text = FormatCurrency(subTotalPrice + taxes)
        lbltaxesPrice.Text = FormatCurrency(taxes)
        MessageBox.Show("Thank you for shopping!", "Thank You", MessageBoxButtons.OK, MessageBoxIcon.Information)
 End If