【问题标题】:Error when converting String to Float/Int. C# Windows Forms将 String 转换为 Float/Int 时出错。 C# Windows 窗体
【发布时间】:2017-01-05 16:49:17
【问题描述】:

我是 C# 的新手。我希望有人可以帮助我。

我正在编写一个小型 Windows 窗体应用程序。 两个文本框和一个结果标签。 几个小时以来,我试图从 textBoxes 中的字符串中获取浮点值。 稍后有人会在 TextBox1 中写入例如 1.25,然后将其除以第二个 TextBox 中的值。

我尝试了很多代码。如果代码正在运行(不是红色下划线),那么我会得到这个

错误消息:“mscorlib.dll 中的错误类型 System.Format.Exception”。 “输入的字符串格式错误”。

我该如何解决这个问题?!还是我做错了什么?!请帮忙。我是菜鸟。

  using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;

    namespace WindowsFormsApplication1
{


    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            string a = textBox1.Text;
            string b = textBox2.Text;

            float num = float.Parse(textBox1.Text);

        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }
    }
}

`

【问题讨论】:

  • 您正在尝试在表单的构造函数中进行计算。在表单的构造函数中,用户尚未输入任何文本。您可能希望您的 float num = float.Parse(textBox1.Text); 包含在 button1_Click 中。
  • 好的,这有帮助!非常感谢!

标签: c# windows forms textbox


【解决方案1】:

如果您使用 Parse 函数并输入了无效数字 - 那么您将收到您描述的类型的错误消息(以未处理异常的形式)。

您可以实现异常处理:

float num;
try
{
    num = float.Parse(textBox1.Text);
}
catch (FormatException)
{
   // report format error here
}

您还可以捕获超出范围和空参数异常:https://msdn.microsoft.com/en-us/library/2thct5cb(v=vs.110).aspx

或者使用 TryParse 方法:

float num;
bool NumberOK = float.TryParse(textBox1.Text, out num);
if (!NumberOK)
{
    // report error here
}

https://msdn.microsoft.com/en-us/library/26sxas5t(v=vs.110).aspx

【讨论】:

  • 我会的。谢谢!
猜你喜欢
  • 2020-08-07
  • 1970-01-01
  • 1970-01-01
  • 2019-12-11
  • 2021-10-12
  • 2019-12-04
  • 2011-08-09
  • 2017-09-04
  • 2011-11-02
相关资源
最近更新 更多