Restrict non-numerical values from operation

时间:2017-04-24 17:34:10

标签: c# .net winforms

I am making a calculator in windows forms and I want to make a message box pop up when the user tries to add/subtract/divide/multiply with non-numerical values. I have looked at the old forums that give possible fixes but none have seemed to work so far.

here is my code for the multiply button:

private void buttonMul_Click(object sender, KeyPressEventArgs e)
{
    Operand1 = Convert.ToDouble(textOperand1.Text);
    Operand2 = Convert.ToDouble(textOperand2.Text);
    result = Operand1 * Operand2;
    textresult.Text = result.ToString();
}

3 个答案:

答案 0 :(得分:2)

当用户输入错误类型的输入时,不要向用户抛出错误,而是阻止他们输入除数字之外的任何内容。

<强>事件

在文本框上使用按键事件,如下所示:

private void textBox_KeyPress(object sender, KeyPressEventArgs e)
{
    // Get reference to calling control
    TextBox textBox = sender as TextBox;

    // Only allow 0-9, ., -
    if (!char.IsControl(e.KeyChar) && 
        !char.IsDigit(e.KeyChar) &&
        e.KeyChar != '-' &&
        e.KeyChar != '.')
    {
        e.Handled = true;
    }

    // Avoid double decimals
    if (e.KeyChar == '.' && textBox.Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }

    // Ensure hyphen is at the beginning
    if (e.KeyChar == '-' && 
        (textBox.Text.Contains('-') || 
        textBox.SelectionStart != 0))
    {
        e.Handled = true;
    }
}

这将只允许输入数值,小数和连字符。此外,这还将阻止输入中超过1个十进制.,并确保用户只能在文本开头输入连字符-

注册EventHandler

要注册此事件处理程序,只需将此行代码添加到表单的构造函数中。

// Be sure to change yourtextcontrol to the appropriate name.
yourtextcontrol.KeyPress += new KeyPressEventHandler(textBox_KeyPress);

验证输入

您还应该在点击事件中使用TryParse来仔细检查条目。

private void buttonMul_Click(object sender, KeyPressEventArgs e)
{
    if (double.TryParse(textOperand1.Text, out Operand1) &&
        double.TryParse(textOperand2.Text, out Operand2)) 
    {
        result = Operand1 * Operand2;
        textresult.Text = result.ToString();
    }
    else
    {
        // Error here. You can use a messagebox or whatever suits you.
    }
}

答案 1 :(得分:2)

如果出于某种原因,他们必须能够为计算器中的某些其他功能输入除数字以外的其他内容。您可以使用TryParse,如果无法解析该值,则会返回false,然后显示消息框

Dim tableCount As Integer
Dim tableNumber As Integer
Dim bookmarkName As String
'
tableCount = ActiveDocument.Tables.Count
'
For tableNumber = tableCount To 1 Step -1
    ActiveDocument.Tables(tableNumber).Select
    *If Selection.Bookmarks(1).Exists = False Then
        GoTo Furthermore
    End If*
    bookmarkName = Selection.Bookmarks(1).Name
    If Left(bookmarkName, 3) = "NTS" Then
        ActiveDocument.Tables(tableNumber).delete
        ActiveDocument.Bookmarks(bookmarkName).delete
    End If
Furthermore:
Next

答案 2 :(得分:0)

您可以使用TryParse方法:https://msdn.microsoft.com/en-us/library/system.single.tryparse.aspx

如果输入不是数值,则返回false。

double result;
if (double.TryParse(textOperand1.Text, out result))
{
   // Do stuff
}