我如何创建一个 catch 以确保在文本框中输入除了数字以外的任何内容,但也接受空白条目

How can I create a catch that ensures nothing other than a number is entered into a textbox but also accepts a blank entry

我有一个文本框。讲师说我必须有一个陷阱以确保输入有效数字以外的任何内容,但文本框是可选的。换句话说,用户可能根本不进行输入。我有一个捕获器可以捕获输入的任何字母,但如果文本框留空它也会捕获。换句话说,它表示必须输入有效数字,即使它是空白的。我怎样才能制作一个不接受任何条目或数字但不接受其他任何东西的渔获物?

这是我的代码的相关部分;

try
{
    if (decimal.Parse(lessTradeInTextBox.Text) > decimal.Parse(vehiclePriceTextBox.Text))
    {
        MessageBox.Show("The trade-in price cannot be greater than the purchase price");
        Keyboard.Focus(lessTradeInTextBox);
    }
    else
    {
        // calculations go here
    }
}
catch (FormatException theException)
{
    MessageBox.Show("Please enter a valid number for the Trade-in   price. \n" + "Reason: " + theException.Message);

    Keyboard.Focus(lessTradeInTextBox);
    lessTradeInTextBox.SelectAll();
}
catch (Exception theException)
{
    MessageBox.Show("Error, GeneralTransform Error. " + theException.Message);
    Keyboard.Focus(lessTradeInTextBox);
    lessTradeInTextBox.SelectAll();
}

更改您的 if 条件以检查空字符串。即

if (!string.IsNullOrEmpty(lessTradeInTextBox.Text) &&
!string.IsNullOrEmpty(vehiclePriceTextBox.Text) &&
(decimal.Parse(lessTradeInTextBox.Text) > decimal.Parse(vehiclePriceTextBox.Text)))

只需在与此特定文本框相关的代码块外部检查您的代码,并允许它绕过其中的所有内容并保持原样。像这样的东西应该对你有帮助:

if(yourTextBox.Text != "")
{
   //your relevant code and all manipulations on that textbox, only if its not null.
}
else
{
    //to do something when textbox.Text is null
}

通过这种方式,如果它为 null,则允许它绕过代码,并且它不会显示 null 情况下的异常。

希望对您有所帮助。

您可以简单地使用像这样的内联 if 语句:

try
{
    string lessTrade = (string.IsNullOrEmpty(lessTradeInTextBox.Text)) ? "0" : lessTradeInTextBox.Text;
    string vehiclePrice = (string.IsNullOrEmpty(vehiclePriceTextBox.Text)) ? "0" : vehiclePriceTextBox.Text;

    if (decimal.Parse(lessTrade) > decimal.Parse(vehiclePrice))
    {
        MessageBox.Show("The trade-in price cannot be greater than the purchase price");
        Keyboard.Focus(lessTradeInTextBox);
    }
    else
    {
        // calculations go here
    }
}
catch (Exception e)
{
    //do your exception handling.
}

使用 try-catch 不是一种经济高效的解决方案。所以我建议使用以下代码:

string lessTrade = (string.IsNullOrEmpty(lessTradeInTextBox.Text)) ? "0" : lessTradeInTextBox.Text;
string vehiclePrice = (string.IsNullOrEmpty(vehiclePriceTextBox.Text)) ? "0" : vehiclePriceTextBox.Text;

decimal lessTradeD, vehiclePriceD;
if (decimal.TryParse(lessTrade, out lessTradeD) & decimal.TryParse(vehiclePrice, out vehiclePriceD))
{
    if (lessTradeD > vehiclePriceD)
    {
        MessageBox.Show("The trade-in price cannot be greater than the purchase price");
        Keyboard.Focus(lessTradeInTextBox);
    }
    else
    {
        // calculations go here
    }
}
else
{
    //wrong input, do your exceptin handling.
}