C#实验三编写一个加法计算器
实验三 .Net中基本控件的编程
编写一个加法计算器:
\1. 点击求和按钮可以求和
\2. 先输入加数,在输入被加数时,边输入边自动求和
\3. 边输入加数或被加数边判断用户输入是否为数字,如果不是数字不显示,并给用户提示。
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void TextBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_keyPressed(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar=='.' || e.KeyChar == '\b' )
{
e.Handled = false;
}
else
{
e.Handled = true;
MessageBox.Show("请输入数字!");
}
}
private void TextBox2_TextChanged(object sender, EventArgs e)
{
try
{
double a = double.Parse(textBox1.Text);
double b = double.Parse(textBox2.Text);
textBox3.Text = (a + b).ToString();
}
catch (Exception wrong)
{
MessageBox.Show("请输入数字!");
wrong.ToString();
}
}
private void textBox2_keyPressed(object sender, KeyPressEventArgs e)
{
if (e.KeyChar >= '0' && e.KeyChar <= '9' || e.KeyChar == '\b' || e.KeyChar == '.')
{
e.Handled = false;
}
else
{
e.Handled = true;
MessageBox.Show("请输入数字!");
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
double a = double.Parse(textBox1.Text);
double b = double.Parse(textBox2.Text);
textBox3.Text = (a + b).ToString();
}
catch (Exception wrong)
{
MessageBox.Show("请输入数字!");
wrong.ToString();
}
}
}
还缺少判断小数点的代码。比如连续输入两个小数点的情况。