简体   繁体   English

文本框上的C#退格立即创建错误

[英]C# backspace on textbox creating errors immediately

I am creating an event where if someone types into a text box it will show an error using this code: 我正在创建一个事件,如果有人在文本框中键入内容,则将使用以下代码显示错误:

try
{
    dblCostSqFt = double.Parse(txtCost.Text);
}
catch
{
    MessageBox.Show("Error. You must enter valid numbers. Please correct.");
    txtCost.Select();
    return;
}

The issue with this is if I input a backspace it will throw that error message immediately I would like to make it to where that doesn't happen. 问题是,如果我输入一个退格键,它将立即抛出该错误消息,我想将其返回到不会发生的地方。

You're working with userinput here. 您正在此处使用userinput。 Therefore i'd suggest to use Double.TryParse() 因此,我建议使用Double.TryParse()

  • If you've got a string, and you expect it to always be a double (say, if some web service is handing you a double in string format), you'd use Double.Parse() . 如果您有一个字符串,并且希望它始终是双Double.Parse()例如,如果某些Web服务以字符串格式为您提供双Double.Parse() ),则可以使用Double.Parse()

  • If you're collecting input from a user, you'd generally use Double.TryParse() , since it allows you more fine-grained control over the situation when the user enters invalid input. 如果要从用户处收集输入,通常应使用Double.TryParse() ,因为当用户输入无效输入时,它可以使您对情况进行更细粒度的控制。

With tryparse() your code will be something like this: 使用tryparse()您的代码将如下所示:

if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
    MessageBox.Show("Error. You must enter valid numbers. Please correct.");
    txtExample.Select(0, txtCost.Text.Length);
    return;
}

To make the example complete and address the issue one could simply check if the Text is not null or empty by using String.IsNullOrEmpty() making the whole code: 为了使示例更完整并解决问题,可以使用String.IsNullOrEmpty()编写整个代码,简单地检查Text是否为null或为empty

// makes sure your app isn't crashing upon backspaces.
if(string.IsNullOrEmpty(textCost.Text))
{
    // Personally i'd indicate the user nothing is typed in (yet).
    return;
}
if (!double.TryParse(txtCost.Text, out var dblCostSqFt))
{
    // The user filled in something that can't be parse to doubles.
    MessageBox.Show("Error. You must enter valid numbers. Please correct.");
    txtExample.Select(0, txtCost.Text.Length);
    return;
}
// All is great; Do stuff with dblCostSqFt.

Assuming you are using WPF for your UI without straying too far from what you have I would use something like below (as LarsTech suggested, use TryParse to test if the value can be converted). 假设您正在为您的UI使用WPF,而又不会偏离您所拥有的东西太远,那么我将使用下面的类似内容(如LarsTech建议的那样,使用TryParse测试值是否可以转换)。 Note the if block surrounding the core code within the function, you can avoid execution entering the if block by checking if the key pressed was backspace. 注意函数中围绕核心代码的if块,可以通过检查所按下的键是否为退格键来避免执行进入if块的操作。 I also added a check for the enter key as many users would press the enter key to close the MessageBox, which would cause the event to trigger once again. 我还为回车键添加了一个检查,因为许多用户会按回车键关闭MessageBox,这将导致事件再次触发。

private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key != Key.Back && e.Key != Key.Enter)
    {
        double dblCostSqFt = 0;

        if (!double.TryParse(txtExample.Text, out dblCostSqFt))
        {
            MessageBox.Show("Error. You must enter valid numbers. Please correct.");
            txtExample.Select(0, txtExample.Text.Length);
        }
    }
}

Never rely on exception handling to control the workflow of your application, exceptions have a ton of overhead and it is typically a bad practice in general. 永远不要依靠异常处理来控制应用程序的工作流程,异常会产生大量开销,通常这通常是一种不好的做法。

You can accomplish the same thing in WinForms as well using the following... 您还可以使用以下方法在WinForms中完成相同的操作:

private void txtExample_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode != Keys.Back && e.KeyCode != Keys.Enter)
    {
        double dblCostSqFt = 0;

        if (!double.TryParse(txtExample.Text, out dblCostSqFt))
        {
            MessageBox.Show("Error. You must enter valid numbers. Please correct.");
            txtExample.Select();
        }
    }
}

It looks like you are using WinForms because your textbox.Select function call does not supply any arguments, only WinForms supports an overload of the select function without any arguments. 您似乎正在使用WinForms,因为您的textbox.Select函数调用不提供任何参数,只有WinForms支持不带任何参数的select函数的重载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM