namespace Exer3
{
public partial class MyCalculator : Form
{
public MyCalculator()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
int num1 = Convert.ToInt32(txtNum1.Text);
int num2 = Convert.ToInt32(txtNum2.Text);
if (txtNum1.Text.Length == 0 & txtNum2.Text.Length == 0)
{
MessageBox.Show("No Input Detected");
txtNum1.Focus();
txtNum2.Focus();
}
else
lblTotal.Text = (num1 + num2).ToString();
}
}
}
当我运行程序并且计算得很好..但是当我尝试将文本框留空并单击添加按钮时,消息框将显示“未检测到输入”,之后程序将开始调试并显示“输入”字符串格式不正确“。请帮忙解决这个问题
答案 0 :(得分:2)
将这些行更改为
int num1 = Convert.ToInt32("0"+txtNum1.Text);
int num2 = Convert.ToInt32("0"+txtNum2.Text);
或使用int.TryParse
答案 1 :(得分:0)
if (txtNum1.Text.Length == 0 && txtNum2.Text.Length == 0)
{
MessageBox.Show("No Input Detected");
txtNum1.Focus();
txtNum2.Focus();
}
else
{
int num1 = Convert.ToInt32(txtNum1.Text);
int num2 = Convert.ToInt32(txtNum2.Text);
lblTotal.Text = (num1 + num2).ToString();
}