gpt4 book ai didi

c# - 输入字符串的格式不正确

转载 作者:IT王子 更新时间:2023-10-29 03:42:58 26 4
gpt4 key购买 nike

我是 C# 的新手,我有一些 Java 的基础知识,但我无法让这段代码正常运行。

这只是一个基本的计算器,但是当我运行程序时 VS2008 给我这个错误:

Calculator

我做了几乎相同的程序,但在 java 中使用 JSwing,它运行得很好。

这是c#的形式:

Form

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

namespace calculadorac
{
public partial class Form1 : Form
{

int a, b, c;
String resultado;

public Form1()
{
InitializeComponent();
a = Int32.Parse(textBox1.Text);
b = Int32.Parse(textBox2.Text);
}

private void button1_Click(object sender, EventArgs e)
{
add();
result();
}

private void button2_Click(object sender, EventArgs e)
{
substract();
result();
}

private void button3_Click(object sender, EventArgs e)
{
clear();
}

private void add()
{
c = a + b;
resultado = Convert.ToString(c);
}

private void substract()
{
c = a - b;
resultado = Convert.ToString(c);
}

private void result()
{
label1.Text = resultado;
}

private void clear()
{
label1.Text = "";
textBox1.Text = "";
textBox2.Text = "";
}
}

可能是什么问题?有办法解决吗?

PS:我也试过了

a = Convert.ToInt32(textBox1.text);
b = Convert.ToInt32(textBox2.text);

但它没有用。

最佳答案

该错误意味着您尝试从中解析整数的字符串实际上并不包含有效整数。

创建表单时,文本框不太可能立即包含有效整数 - 这是您获取整数值的地方。在按钮单击事件中更新 ab 会更有意义(与您在构造函数中的方式相同)。另外,查看 Int.TryParse方法 - 如果字符串实际上可能不包含整数,它会更容易使用 - 它不会抛出异常,因此更容易从中恢复。

关于c# - 输入字符串的格式不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8321514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com