C#實驗三

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();
            }
        }
    }

還缺少判斷小數點的代碼。比如連續輸入兩個小數點的情況。


發佈了71 篇原創文章 · 獲贊 40 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章