c# - 如何防止 C# 中因无效输入而崩溃

标签 c# .net winforms error-handling int

我制作了一个简单的应用程序来将 2 个数字相加,但是当我将两个字母或无效符号相加时,程序就会崩溃。如何创建一个消息框,当有人插入字母时显示“请输入数字”内容

这是我的代码:

public partial class frmAdd : Form
{
    string first;
    string second;
    public frmAdd()
    {
        InitializeComponent();
    }

    private void btnFirst_Click(object sender, EventArgs e)
    {
        first = txtNumber.Text;
    }

    private void btnSecond_Click(object sender, EventArgs e)
    {
        second = txtNumber.Text;
    }

    private void btnResult_Click(object sender, EventArgs e)
    {
        int a = Convert.ToInt32(first);
        int b = Convert.ToInt32(second);
        int c = a + b;
        txtResult.Text = c.ToString();
    }
}

最佳答案

使用TryParse相反:

private void btnResult_Click(object sender, EventArgs e)
{
    int a, b;
    if (int.TryParse(first, out a) && int.TryParse(second, out b))
    {
        int c = a + b;
        txtResult.Text = c.ToString();
    } 
    else
    {
        MessageBox.Show("Invalid Input!");
    }
}

或者也许更好的方法是在用户第一次输入数据时捕获错误:

public partial class frmAdd : Form 
{ 
    int first;   // changed to int
    int second;

    private void btnFirst_Click(object sender, EventArgs e)
    {
        if (!int.TryParse(txtNumber.Text, out this.first))
        {
            MessageBox.Show("Invalid Input!");
        }
    }

    private void btnSecond_Click(object sender, EventArgs e)
    {
        if (!int.TryParse(txtNumber.Text, out this.second))
        {
            MessageBox.Show("Invalid Input!");
        }
    }

    private void btnResult_Click(object sender, EventArgs e)
    {
        int c = first + second;
        txtResult.Text = c.ToString();
    }
}

关于c# - 如何防止 C# 中因无效输入而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18369081/

相关文章:

c# - Azure Pipelines 选项内部版本号 : Does $(Rev:r) increment on every build?

c# - 如何在 const 字符串中包含枚举值?

c# - C# 中的 CircularBuffer IDictionary?

c# - 如何在 C# 中设置图像大小限制(例如;<150kb)

C# Web浏览器锚定

c# - "Name ' 在控制台应用程序中处理 ' does not exist in current context"错误

c# - Nuget 库的多运行时目标

c# - JIT 拒绝内联微型方法

c# - 切换画笔颜色的更好方法?

c# - 添加到我的 UserControl 的 TabControl 的 TabPage 的控件在重建后消失