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 }
时间: 2024-10-10 07:00:27