【发布时间】:2017-09-15 00:09:06
【问题描述】:
我是 C# 的新手,这是我第一次尝试创建 Windows 窗体。我创建了一个非常简单的计算器,它有两个文本框供用户输入数字。它有一个(n)加、减、乘和除按钮,当用户在文本框中输入值并单击其中一个按钮时,结果会显示在标签中。我只想允许将整数输入到文本框中,但我不知道我将如何做到这一点。任何意见或建议表示赞赏。谢谢。
到目前为止,这是我的代码:
namespace SimpleCalc
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void AddBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text)).ToString();
}
private void SubtractBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) - Convert.ToInt32(textBox2.Text)).ToString();
}
private void MultiplyBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) * Convert.ToInt32(textBox2.Text)).ToString();
}
private void DivideBtn_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text))
ResultLbl.Text = (Convert.ToInt32(textBox1.Text) / Convert.ToInt32(textBox2.Text)).ToString();
}
}
}
【问题讨论】:
-
如果是计算器,NumericUpDowns 可能更合适。它们仍然不是整数,但不允许字母。请阅读How to Ask 并采取tour