【案例】本案例在一个窗体中实现供儿童做的两个一位数相加的练习器。在窗体中能自动产生一道随机的两个一位数相加的练习。
1.添加4个Label控件,1个Button控件,1个TextBox控件。
2.后台代码如下:
namespace WindowsFormsApp4 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { int n; Random randomNumber = new Random(); n = randomNumber.Next(10); lblNum1.Text = n.ToString(); n = randomNumber.Next(10); lblNum2.Text = n.ToString(); } private void txtResult_KeyPress(object sender, KeyPressEventArgs e) { if(!(Char.IsDigit (e.KeyChar )==true || e.KeyChar == 8)) { e.Handled = true; } if(e.KeyChar == 13) { if (txtResult.Text == string.Empty) { MessageBox.Show("计算结果不能为空"); return; } else { int result = int.Parse(lblNum1.Text) + int.Parse(lblNum2.Text); int myresult = int.Parse(txtResult.Text); if (result == myresult) { MessageBox.Show("恭喜你,答对了"); Form1_Load(null, null); } else { MessageBox.Show("对不起,打错了,请再来一次"); } } } } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } } }
运行结果如下图所示: