.
NET C#
Research Topic:
C# Windows Forms Calculator Application
Bachelor Degree
Major: Computer Science
Batch: 22
Research by:
Orm Savuth
Professor: San Bunna
1
Academic Year: 2025 - 2026
Preface
We warmly welcome all friends, students, researchers, and readers interested in
exploring this document. It is with deep appreciation that we present the research work
conducted under the valuable guidance of Professor San Bunna, whose expertise and
encouragement greatly enriched our study.
This document is the result of both extensive research and careful compilation, drawn
from trusted sources including academic libraries and online references. While it may
not cover every detail exhaustively, we hope it serves as a strong foundation for future
learning and exploration.
We acknowledge that despite our best efforts, there may be minor errors or omissions.
We sincerely invite suggestions, corrections, and feedback from teachers, professors,
students, and future readers to help us further improve the quality of this work.
Finally, we wish everyone abundant blessings, continuous learning, and success in both
academic and personal journeys. May this document contribute positively to your
growth and understanding.
1
Table of Contents
1. Overview
2. Project Structure
3. Key Components
4. User Interface
5. Code Explanation
Class and Variables
Constructor
Helper Methods
Event Handlers
6. How to Use the Calculator
7. Error Handling
8. Conclusion
2
Overview
The Calculator application is a Windows Forms project written in C# that mimics a basic
calculator. It allows users to:
Login experience
Input numbers and decimal points.
Perform arithmetic operations: addition (+), subtraction (-), multiplication (×), and
division (÷).
Calculate percentages.
Clear the input, delete the last digit (backspace), or exit the application.
View the current expression and a dynamic result preview during calculations.
The application uses a graphical user interface (GUI) created with Windows Forms,
where buttons trigger specific actions, and results are displayed in text boxes and
labels.
3
Project Structure
The project is contained within the FrmCalculator_Project namespace and consists of a
single class, Calculator, which inherits from System.Windows.Forms.Form. The form is
designed using the Windows Forms Designer, and the logic is implemented in the
Calculator.cs file.
Key files:
Calculator.cs: Contains the code logic for the calculator’s functionality.
Calculator.Designer.cs: Auto-generated file containing the UI component
initialization (e.g., buttons, text boxes, labels).
Login.cs: Implements the Login class, which may include methods for validating
credentials.
Program.cs: Entry point for the application, launching the Calculator form
4
User Interface
The UI consists of:
A TextBox (txtResult) for displaying the current input or result.
A Label (lblExpression) for showing the ongoing expression.
Buttons for:
Digits (0–9): Input numbers.
Operators (+, -, ×, ÷): Select the arithmetic operation.
Decimal point (.): Add a decimal to the current number.
Percentage (%): Calculate a percentage based on the context.
Clear (C): Reset the calculator.
Backspace: Remove the last digit.
Equal (=): Compute the final result.
Exit: Close the application.
The layout is typically arranged in a grid, similar to a physical calculator, designed using
the Windows Forms Designer.
5
Code Explanation
Class and Variables
The Calculator class is defined as a partial class inheriting from Form. It contains the
following fields:
float num1, ans; // num1 = first number, ans = running total int count; // Operator:
1=subtract, 2=add, 3=multiply, 4=divide bool isOperatorPressed = false; string
expression = ""; // Store the full expression for display
num1: Initially stores the first number; later used to store intermediate results.
ans: Holds the running total of calculations.
count: Tracks the selected operator (0 = none, 1 = subtract, 2 = add, 3 = multiply,
4 = divide).
isOperatorPressed: Ensures the txtResult is cleared when a new number is
entered after an operator.
expression: Builds the string shown in lblExpression.
Constructor
public Calculator()
InitializeComponent();
The constructor calls InitializeComponent(), which sets up the UI components defined in
Calculator.Designer.cs.
Helper Methods
1. AppendDigit(string digit):
Appends a digit (0–9) to txtResult.
Clears txtResult if an operator was recently pressed (isOperatorPressed = true).
Updates the dynamic result preview if an operator is active.
private void AppendDigit(string digit)
if (isOperatorPressed)
6
txtResult.Clear();
isOperatorPressed = false;
txtResult.Text += digit;
if (count > 0 && float.TryParse(txtResult.Text, out _))
UpdateDynamicResult();
2. UpdateDynamicResult():
Computes and displays a temporary result as the user types the second number.
Uses the current operator (count) and running total (ans) to calculate the result.
Updates lblExpression with the intermediate result.
Handles potential parsing errors silently
private void UpdateDynamicResult()
try
float num2 = float.Parse(txtResult.Text);
float tempAns = ans;
switch (count)
case 1: tempAns -= num2; break;
case 2: tempAns += num2; break;
case 3: tempAns *= num2; break;
case 4: if (num2 != 0) tempAns /= num2; break;
7
lblExpression.Text = $"{expression} {num2} = {tempAns}";
catch
// Ignore parsing errors
}.
3. GetOperatorSymbol(int count):
Returns the symbol for the operator (-, +, ×, ÷) based on the count value.
private string GetOperatorSymbol(int count)
switch (count)
case 1: return "-";
case 2: return "+";
case 3: return "×";
case 4: return "÷";
default: return "";
4. ProcessOperation(int newCount):
Processes the current number and operator, updating ans and expression.
Performs the previous operation (if any) before setting the new operator.
Handles errors like division by zero.
8
private void ProcessOperation(int newCount)
{
if (string.IsNullOrWhiteSpace(txtResult.Text)) return;
try
float num2 = float.Parse(txtResult.Text);
if (count == 0)
{
ans = num2;
else
switch (count)
case 1: ans -= num2; break;
case 2: ans += num2; break;
case 3: ans *= num2; break;
case 4: if (num2 == 0) throw new DivideByZeroException("Cannot divide
by zero"); ans /= num2; break;
expression += $" {num2} {GetOperatorSymbol(newCount)}";
lblExpression.Text = expression;
count = newCount;
isOperatorPressed = true;
}
catch (Exception ex)
MessageBox.Show("Error: " + ex.Message);
9
}
Event Handlers
1. Digit Buttons (0–9):
Each digit button calls AppendDigit with the corresponding digit.
private void btnzero_Click(object sender, EventArgs e) => AppendDigit("0");
// Similarly for btnone_Click, btntwo_Click, etc.
2. Clear Button:
Resets all variables and UI elements to their initial state.
private void btnclear_Click(object sender, EventArgs e)
txtResult.Clear();
lblExpression.Text = "";
expression = "";
count = 0;
num1 = 0;
ans = 0;
isOperatorPressed = false;
3. Backspace Button:
Removes the last character from txtResult and updates the dynamic result if
applicable.
private void btnbackspace_Click(object sender, EventArgs e)
if (txtResult.Text.Length > 0)
txtResult.Text = txtResult.Text.Substring(0, txtResult.Text.Length - 1);
if (count > 0 && float.TryParse(txtResult.Text, out _))
{
10
UpdateDynamicResult();
else if (txtResult.Text == "")
lblExpression.Text = expression;
4. Operator Buttons (+, -, ×, ÷):
Each operator button calls ProcessOperation with the corresponding count value
(1–4).
private void btnplus_Click(object sender, EventArgs e) => ProcessOperation(2);
private void btnminus_Click(object sender, EventArgs e) => ProcessOperation(1);
private void btnmultiply_Click(object sender, EventArgs e) => ProcessOperation(3);
private void btndivide_Click(object sender, EventArgs e) => ProcessOperation(4);
5. Decimal Point Button:
Adds a decimal point to txtResult if it doesn’t already contain one.
private void btnperiod_Click(object sender, EventArgs e)
if (!txtResult.Text.Contains("."))
txtResult.Text += ".";
11
6. Equal Button:
Computes the final result based on the current operator and number, displays it,
and resets for a new calculation.
private void btnequal_Click(object sender, EventArgs e)
if (count == 0 || string.IsNullOrWhiteSpace(txtResult.Text)) return;
try
float num2 = float.Parse(txtResult.Text);
switch (count)
case 1: ans -= num2; break;
case 2: ans += num2; break;
case 3: ans *= num2; break;
case 4: if (num2 == 0) throw new DivideByZeroException("Cannot divide by zero");
ans /= num2; break;
expression += $" {num2} =";
lblExpression.Text = expression;
txtResult.Text = ans.ToString();
count = 0;
expression = "";
num1 = ans;
catch (Exception ex)
MessageBox.Show("Error: " + ex.Message);
12
7. Percentage Button:
Calculates a percentage based on the current operator context (e.g., for
addition/subtraction, it computes ans * (currentValue / 100); for
multiplication/division, it computes currentValue / 100).
private void button1_Click(object sender, EventArgs e)
if (float.TryParse(txtResult.Text, out float currentValue))
switch (count)
case 1: case 2: currentValue = ans * (currentValue / 100f); break;
case 3: case 4: currentValue = currentValue / 100f; break;
default: currentValue = currentValue / 100f; break;
txtResult.Text = currentValue.ToString("N2");
if (count > 0)
UpdateDynamicResult();
8. Exit Button:
Closes the application.
private void btnexit_Click(object sender, EventArgs e)
Application.Exit();
13
How to Use the
Calculator
Starting the Calculator:
Run the application in Visual Studio or from the compiled executable.
The calculator window appears with a blank txtResult and lblExpression.
Entering Numbers:
Click digit buttons (0–9) to input a number.
Use the decimal point button (.) to add a decimal (only one per number).
Performing Operations:
Enter the first number, then click an operator button (+, -, ×, ÷).
Enter the second number; the lblExpression shows a dynamic result preview.
Click another operator to chain calculations or the equal button (=) to finalize.
Using Percentage:
After entering a number, click the % button to convert it to a percentage.
For addition/subtraction, it calculates ans * (number / 100).
For multiplication/division or no operator, it calculates number / 100.
Clearing and Correcting:
Click the Clear (C) button to reset everything.
Click Backspace to remove the last digit.
Exiting:
Click the Exit button to close the application.
14
Error Handling
The calculator handles the following errors:
Division by Zero: Displays a message box with “Cannot divide by zero” if the
user attempts to divide by 0.
Invalid Input: Uses float.TryParse to safely parse input, preventing crashes from
non-numeric input.
Empty Input: Ignores operations if txtResult is empty.
Errors are displayed via MessageBox.Show for user feedback.
15
Conclusion
This C# Windows Forms Calculator is a robust, user-friendly application for basic
arithmetic operations. It demonstrates key programming concepts such as event-driven
programming, error handling, and dynamic UI updates. By following this manual,
students can understand the code structure, operate the calculator, and explore ways to
extend its functionality for more advanced applications.
16