1 private void txtNumber1_KeyPress(object sender, KeyPressEventArgs e) 2 { 3 //MessageBox.Show(((int)(e.KeyChar)).ToString()); //ASCii查看 4 //由於本事件可能有多個文本框的觸發,所以要通過sender來得到觸發該事件的控件 5 TextBox currentTextBox = sender as TextBox; 6 7 if (e.KeyChar < '0' || e.KeyChar > '9') 8 { 9 e.Handled = true; 10 } 11 if (e.KeyChar == 46)//讓用戶可以輸入小數點 12 { 13 //檢測這個number1文本框中是否已經包含小數點 14 if (currentTextBox.Text.IndexOf(".") == -1) 15 { 16 //光標不能在第一位,也就是說小數點不能出現在第一位 17 if (currentTextBox.SelectionStart > 0) 18 { 19 e.Handled = false; 20 } 21 } 22 } 23 if (e.KeyChar == 8) //讓用戶可以輸入退格鍵 24 { 25 e.Handled = false; 26 } 27 28 } 29 30 private void btnResult_Click(object sender, EventArgs e) 31 { 32 try 33 { 34 double number1 = Convert.ToDouble(txtNumber1.Text); 35 double number2 = Convert.ToDouble(txtNumber2.Text); 36 37 switch (comboBox1.Text) 38 { 39 case "加": 40 lbResult.Text = (number1 + number2).ToString(); 41 break; 42 case "減": 43 lbResult.Text = (number1 - number2).ToString(); 44 break; 45 case "乘": 46 lbResult.Text = (number1 * number2).ToString(); 47 break; 48 case "除": 49 lbResult.Text = (number1 / number2).ToString(); 50 break; 51 } 52 } 53 catch(Exception ex) 54 { 55 MessageBox.Show("你的輸入有問題"+ex.Message); 56 } 57 } 58 59 private void txtNumber1_TextChanged(object sender, EventArgs e) 60 { 61 lbResult.Text = " "; 62 } 63 64 private void frmFourOperations_Load(object sender, EventArgs e) 65 { 66 comboBox1.SelectedIndex = 0; //當combobox的dropdownstyle屬性設置為list時 將無法在屬性寫入初始值 需要通過該語句實現 67 }