C#基本上上是視覺化的程式語言,和Visual Basic很像,只是它繼承了C++的語法,用C#來開發視窗程式很直覺,也很方便。
這個程式主要是練習C#元件的基本操作: 建立3個文字方塊,5個按鍵,作兩個數字的四則運算。其中比較值得注意的是Error Handling的部分(紅色文字),在使用者輸入錯誤時,可以攔截並做對應處理,防止程式和系統錯亂。另外,this指的是成本身,所以this.Close(); 就是關閉程式,Double.Parse() 是用來將字串轉成數字,ToString() 是把數字轉成字串,以方便文字方塊顯示。
視窗畫面
底下是程式碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace P20160314_2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnAdd_Click(object sender, EventArgs e)
{
Double r;
try
{
r = Double.Parse(txtNum1.Text) + Double.Parse(txtNum2.Text);
txtResult.Text = r.ToString();
}
catch (Exception err)
{
MessageBox.Show("Wrong Input!!!");
txtNum1.Text = "";
txtNum2.Text = "";
txtResult.Text = "";
};
}
private void btnSub_Click(object sender, EventArgs e)
{
Double r;
try
{
r = Double.Parse(txtNum1.Text) - Double.Parse(txtNum2.Text);
txtResult.Text = r.ToString();
}
catch (Exception err)
{
MessageBox.Show("Wrong Input!!!");
txtNum1.Text = "";
txtNum2.Text = "";
txtResult.Text = "";
};
}
private void btnMul_Click(object sender, EventArgs e)
{
Double r;
try
{
r = Double.Parse(txtNum1.Text) * Double.Parse(txtNum2.Text);
txtResult.Text = r.ToString();
}
catch (Exception err)
{
MessageBox.Show("Wrong Input!!!");
txtNum1.Text = "";
txtNum2.Text = "";
txtResult.Text = "";
};
}
private void btnDiv_Click(object sender, EventArgs e)
{
Double r;
try
{
r = Double.Parse(txtNum1.Text) / Double.Parse(txtNum2.Text);
txtResult.Text = r.ToString();
}
catch (Exception err)
{
MessageBox.Show("Wrong Input!!!");
txtNum1.Text = "";
txtNum2.Text = "";
txtResult.Text = "";
};
}
}
}
沒有留言:
張貼留言