输入字符串的格式不正确(c#简单方法)

本文关键字:简单 方法 不正确 字符串 格式 输入 | 更新日期: 2024-04-23 15:07:51

我知道这件事有很多线程,但我找不到有效的解决方案。我对c#很陌生,所以我不完全确定该怎么办。基本上,这种方法是,当用户在textRetreat.text文本字段中输入值时,他们要么会因为输入字母等而收到错误,要么会显示一条消息,显示他们要提取的金额。我仍在研究这个方法,以提高它的效率。txtBalance.text是用户现有的余额,以防有人想知道它的用途。这是我得到错误的代码部分。

error= double numberEntered = double.Parse(txtWithdraw.Text);
whole method
private void newBalance()
    {
        double numberEntered = double.Parse(txtWithdraw.Text);
        double balance = double.Parse(txtBalance.Text);
      double newBalance = balance - numberEntered;
        txtBalance.Text=((balance - numberEntered).ToString());
      if (numberEntered < 1 || numberEntered > 9999999)
        {
            MessageBox.Show("You must enter a number between 1 and 10");
        }
        else
        MessageBox.Show(String.Format(numberEntered.ToString()), "You have withdrawn");
        txtWithdraw.Text = "";
        // MessageBox.Show(newBalance.ToString(),numberEntered.ToString());
    }

输入字符串的格式不正确(c#简单方法)

使用Double.TryParse方法检查字符串是否可以解析为Double。此方法返回布尔值,而不是引发异常。如果数据格式错误,请检查此值并通知用户:

private void newBalance()
{      
    double withdraw;
    if (!double.TryParse(txtWithdraw.Text, out withdraw));
    {
        MessageBox.Show("Please, enter correct withdraw number");
        return;
    }
    if (withdraw < 1 || 9999999 < withdraw)
    {
        MessageBox.Show("You must enter a number between 1 and 10");
        return;
    }
    double balance;
    if (!double.TryParse(txtBalance.Text, out balance));
    {
        MessageBox.Show("Please, enter correct balance number");
        return;
    }
    balance -= withdraw;
    txtBalance.Text = balance.ToString();
    MessageBox.Show(String.Format(withdraw.ToString()), "You have withdrawn");
    txtWithdraw.Text = "";
}

我还建议您处理文本框的Validating事件,以检查值在输入后的格式是否正确。请参阅Windows窗体中的用户输入验证。或者使用NumericUpDown控件来避免非数字输入。

您可以使用Double.TryParse()函数来检查给定的输入是否可以转换为双精度。

来自MSDN:Double.TryParse()

以指定的样式转换数字的字符串表示形式及其双精度浮点的区域性特定格式数量相等。返回值指示转换是否成功或失败。

试试这个:

private void newBalance()
{
   double numberEntered ;
   double balance ; 
   if(double.TryParse(txtWithdraw.Text,System.Globalization.NumberStyles.None,System.Globalization.CultureInfo.InvariantCulture,out numberEntered))
   {
     if(double.TryParse(txtBalance.Text,System.Globalization.NumberStyles.None,System.Globalization.CultureInfo.InvariantCulture,out balance))
     {
        double newBalance = balance - numberEntered;
        txtBalance.Text=((balance - numberEntered).ToString());
        if (numberEntered < 1 || numberEntered > 9999999)
        {
            MessageBox.Show("You must enter a number between 1 and 10");
        }
        else
        MessageBox.Show(String.Format(numberEntered.ToString()), "You have withdrawn");
        txtWithdraw.Text = "";
        // MessageBox.Show(newBalance.ToString(),numberEntered.ToString());
     }
   }
}