he following C# code is for a simple calculator. In this tutorial we will use Visual Studio and the WPF to build simple calculator that perform addition, subtraction, multiplication and division on floating point number. C# Calculator Example in WPF Form App
1. Create a New C# Windows WPF Application named similar to MyCalc
2. Design the form similar to that shown above
3. Set the properties of each control on following values
- TextBox -> txtOperand1
- TextBox -> txtOperand2
- TextBox -> txtAnswer
- Button -> btnAdd
- Button -> btnSubtract
- Button -> btnMultiply
- Button -> btnDivide
4. Double click on btnAdd and add this code
1 2 3 4 5 6 7 8 9 10 11 12 13 | try { float num1 = Convert.ToSingle(txtOperand1.Text); float num2 = Convert.ToSingle(txtOperand2.Text); txtAnswer.Text = (num1 + num2).ToString(); } catch (Exception) { MessageBox.Show("Enter only numeric values"); } |
5. Double click on btnSubtract and add this code
1 2 3 4 5 6 7 8 9 10 11 12 13 | try { float num1 = Convert.ToSingle(txtOperand1.Text); float num2 = Convert.ToSingle(txtOperand2.Text); txtAnswer.Text = (num1 - num2).ToString(); } catch (Exception) { MessageBox.Show("Enter only numeric values"); } |
6. Double click on btnMultiply and add this code
1 2 3 4 5 6 7 8 9 10 11 12 13 | try { float num1 = Convert.ToSingle(txtOperand1.Text); float num2 = Convert.ToSingle(txtOperand2.Text); txtAnswer.Text = (num1 * num2).ToString(); } catch (Exception) { MessageBox.Show("Enter only numeric values"); } |
7. Double click on btnDivide and add this code
1 2 3 4 5 6 7 8 9 10 11 12 13 | try { float num1 = Convert.ToSingle(txtOperand1.Text); float num2 = Convert.ToSingle(txtOperand2.Text); txtAnswer.Text = (num1 / num2).ToString(); } catch (Exception) { MessageBox.Show("Enter only numeric values"); } |