c#编写简单计算器

刚接触c#,依照惯例,写个简单的计算器,只写了加法,乘法,其他的类似,编辑器用的vs2008

首先打开vs ,新建c#的Windows窗体应用程序,接下来的项目的名称是WindowsFormsApplication2,不是WindowsFormsApplication3。

然后设计计算器的ui界面,比较简单,请谅解。。。

接下来就是编码,首先要给按钮增加点击事件,代码如下:

button1.Click += new EventHandler(Btns_Click);
button2.Click += new EventHandler(Btns_Click);

但是这两行代码不能单独放在代码里,需要放在一个方法里面;

private void addOperatorBtns()
{

button1.Click += new EventHandler(Btns_Click);
button2.Click += new EventHandler(Btns_Click);

}

然后还要声明该方法:

private void Form1_Load(object sender, EventArgs e)
{
addOperatorBtns();
}

接下来就是该点击事件方法的代码实现:

private void Btns_Click(object sender, EventArgs e) //按钮Click事件
{

Button m_CurBtn = (Button)sender;
switch (m_CurBtn.Name)
{
case "button1":
{
a = double.Parse(textBox1.Text);
b = double.Parse(textBox2.Text);
c = a + b;

textBox3.Text = c+" "; 
break;
}
case "button2":
{
a = double.Parse(textBox1.Text);
b = double.Parse(textBox2.Text);
c = a * b;

textBox3.Text = c + " "; 
break;
}

}

}

 

最后 Form1.cs里面的全部代码如下:

   

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 WindowsFormsApplication2
{
public partial class Form1 : Form
{

double a = 0;
double b = 0;
double c = 0;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
addOperatorBtns();
}

private void label1_Click(object sender, EventArgs e)
{

}

private void addOperatorBtns()
{

button1.Click += new EventHandler(Btns_Click);
button2.Click += new EventHandler(Btns_Click);

}

private void Btns_Click(object sender, EventArgs e) //按钮Click事件
{

Button m_CurBtn = (Button)sender;
switch (m_CurBtn.Name)
{
case "button1":
{
a = double.Parse(textBox1.Text);
b = double.Parse(textBox2.Text);
c = a + b;

textBox3.Text = c+" "; 
break;
}
case "button2":
{
a = double.Parse(textBox1.Text);
b = double.Parse(textBox2.Text);
c = a * b;

textBox3.Text = c + " "; 
break;
}

}

}

private void button2_Click(object sender, EventArgs e)
{

}

 

 

}
}

 

posted @ 2016-07-15 17:35  进军的蜗牛  阅读(1017)  评论(0编辑  收藏  举报