【发布时间】: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中。 -
好的,这有帮助!非常感谢!