I'm trying to build a simple calculator application in C# and I have no idea why it crashes when I do the following steps.
Enter 0.2
Click Subtraction
Enter 0
The application crashes immediately. I assume it is something to do with the Zero() function since that is what is executed when the Zero button is clicked. The conditional statements are meant to take care of instances where shouldn't occur like consecutive ciphers and so on. Here is the source code. The functions for the other digits are identical, by the way.
public partial class MainWindow : Window
{
protected double firstNumber, secondNumber;
protected string textBoxContents;
protected int selectedFunction;
public MainWindow()
{
InitializeComponent();
firstNumber = 0;
secondNumber = 0;
selectedFunction = 0;
textBoxContents = "0";
}
private void Zero(object sender, RoutedEventArgs e)
{
if (Convert.ToDouble(textBoxContents) > 0 || textBoxContents[textBoxContents.Length - 1] == '.')
{
if(selectedFunction != 0)
textBoxContents = textBoxContents + "0";
}
else if (textBoxContents == null)
{
textBoxContents = textBoxContents + "0";
}
ResultBox.Content = textBoxContents;
}
private void One(object sender, RoutedEventArgs e)
{
textBoxContents = textBoxContents + "1";
ResultBox.Content = textBoxContents;
}
private void Decimal(object sender, RoutedEventArgs e)
{
textBoxContents = textBoxContents + ".";
ResultBox.Content = textBoxContents;
}
private void Addition(object sender, RoutedEventArgs e)
{
firstNumber = Convert.ToDouble(textBoxContents);
textBoxContents = null;
selectedFunction = 1;
}
private void Subtraction(object sender, RoutedEventArgs e)
{
firstNumber = Convert.ToDouble(textBoxContents);
textBoxContents = null;
selectedFunction = 2;
}
private void Multiplication(object sender, RoutedEventArgs e)
{
firstNumber = Convert.ToDouble(textBoxContents);
textBoxContents = null;
selectedFunction = 3;
}
private void Division(object sender, RoutedEventArgs e)
{
firstNumber = Convert.ToDouble(textBoxContents);
textBoxContents = null;
selectedFunction = 4;
}
private void Result(object sender, RoutedEventArgs e)
{
secondNumber = Convert.ToDouble(textBoxContents);
double thirdNumber = 0;
switch (selectedFunction)
{
case 1:
thirdNumber = firstNumber + secondNumber;
break;
case 2:
thirdNumber = firstNumber - secondNumber;
break;
case 3:
thirdNumber = firstNumber * secondNumber;
break;
case 4:
thirdNumber = firstNumber / secondNumber;
break;
default:
break;
}
textBoxContents = Convert.ToString(thirdNumber);
ResultBox.Content = textBoxContents;
}
private void ClearEverything(object sender, RoutedEventArgs e)
{
textBoxContents = null;
firstNumber = 0;
secondNumber = 0;
selectedFunction = 1;
ResultBox.Content = Convert.ToString(0);
}
private void ToggleNegative(object sender, RoutedEventArgs e)
{
if (Convert.ToDouble(textBoxContents) != 0)
{
textBoxContents = Convert.ToString(Convert.ToDouble(textBoxContents) * -1);
ResultBox.Content = textBoxContents;
}
else
ResultBox.Content = Convert.ToString(0);
}
}
private void Zero(object sender, RoutedEventArgs e)
{
if (Convert.ToDouble(textBoxContents) > 0 ||
textBoxContents[textBoxContents.Length - 1] == '.')
{
if(selectedFunction != 0)
textBoxContents = textBoxContents + "0";
}
else if (textBoxContents == null)
{
textBoxContents = textBoxContents + "0";
}
ResultBox.Content = textBoxContents;
}
That logic seems a tidge off. If the value of the text box is empty then it's going to blow up because of the indexer on the other side of the ||. I think this can be rewritten to say:
private void Zero(object sender, RoutedEventArgs e)
{
var dblVal = Convert.ToDouble(textBoxContents.Text);
textBoxContents.Text = dblVal.ToString();
ResultBox.Content = textBoxContents.Text;
}
In other words, if the text box is empty the conversion will yield 0.0; if it ends in a 1. it will yield 1.0; if it's .5 it will yield 0.5. Just leverage the Convert.
The decimal separator is localized, are you sure that you are using the right culture ("," instead of ".")?
If that's the issue, check out this Stack Question
textBoxContents is null after clicking on the substraction button.
Instead of textBoxContents = null; use textBoxContents = "0"; or textBoxContents = string.Empty;. Why do you set it to null anyway?
Calling textBoxContents.Length in your Zero method causes a NullReferenceException.
As others mentioned before your logic in Zero() seams a bit circuitous and and certainly could be smaller.
in Subtraction function you are doing
textBoxContents = null;
and then in zero you have
textBoxContents[textBoxContents.Length - 1]
thats why it crashes
you should check for null before any operation on textBoxContents
Related
This is a simple calculator program I am trying to make using Windows Forms Application in VS. The UnhandledException appears when I click anywhere except on the calculator buttons. I am fairly new to C# and it seems that a sender button in my function "common_operators" is causing the exception. Also, I want this calculator to have similar memory functionalities as windows 10's built-in calculator. I've searched everywhere but couldn't find a c# calculator implementation that is similar to Win10's built-in calculator has, I have already started but I think there's a better way to implement it. If u need more info, I've uploaded the "designer.cs" file that relates to the form application.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp_Calculator;
namespace WindowsFormsApp_Calculator
{
public partial class CalculatorBase : Form
{
public double[] arrMemory = new double[5];
public int indexer = 0;
double result = 0;
string asmd_operator = ""; // ASMD - Addition, Subtraction, Multiplication, Division
bool insert_value = false;
public CalculatorBase()
{
InitializeComponent();
btn_mc.Enabled = false;
btn_mr.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void numbers_zerotonine(object sender, EventArgs e)
{
Button b = (Button)sender;
if((box_display.Text == "0") || insert_value)
box_display.Text = "";
insert_value = false;
box_display.Text = box_display.Text + b.Text;
}
private void common_operators(object sender, EventArgs e)
{
Button b = (Button)sender;
if (result != 0)
{
btn_eql.PerformClick();
insert_value = true;
asmd_operator = b.Text;
subbox_display.Text = result + " " + asmd_operator;
}
else
{
asmd_operator = b.Text;
result = double.Parse(box_display.Text);
box_display.Text = "";
subbox_display.Text = System.Convert.ToString(result) + " " + asmd_operator;
}
}
private void btn_ce_Click(object sender, EventArgs e)
{
box_display.Text = "0";
}
private void btn_c_Click(object sender, EventArgs e)
{
box_display.Text = "0";
subbox_display.Text = "";
result = 0;
}
private void btn_eql_Click(object sender, EventArgs e)
{
subbox_display.Text = "";
switch(asmd_operator)
{
case "-":
box_display.Text = (result - double.Parse(box_display.Text)).ToString();
break;
case "+":
box_display.Text = (result + double.Parse(box_display.Text)).ToString();
break;
case "X":
box_display.Text = (result * double.Parse(box_display.Text)).ToString();
break;
case "/":
box_display.Text = (result / double.Parse(box_display.Text)).ToString();
break;
default:
break;
}
result = double.Parse(box_display.Text);
asmd_operator = "";
}
private void btn_bs_Click(object sender, EventArgs e)
{
if(box_display.Text.Length > 0)
{
box_display.Text = box_display.Text.Remove(box_display.Text.Length - 1, 1);
}
if(box_display.Text == "")
{
box_display.Text = "0";
}
}
private void btn_ms_Click(object sender, EventArgs e)
{
if (indexer == 5)
{
mem_textbox.Text = "Memory is full. Max limit = 5";
}
else
{
int hgt = 75;
mem_textbox.Text = "";
arrMemory[indexer] = double.Parse(box_display.Text);
indexer++;
btn_mc.Enabled = true;
btn_mr.Enabled = true;
TextBox mem = new TextBox();
mem.Multiline = true;
mem.TextAlign = HorizontalAlignment.Right;
mem.Width = 275;
mem.Height = 70;
mem.Font = new Font(mem.Font.FontFamily, 20);
mem.Text = box_display.Text;
mem.Location = new Point(387, hgt);
this.Controls.Add(mem);
}
}
private void btn_mc_Click(object sender, EventArgs e)
{
foreach (int i in arrMemory)
{
arrMemory[i] = 0;
}
indexer = 0;
btn_mr.Enabled = false;
btn_mc.Enabled = false;
mem_textbox.Text = "There's nothing saved in memory";
}
private void btn_mr_Click(object sender, EventArgs e)
{
box_display.Text = arrMemory[indexer].ToString();
}
private void btn_mp_Click(object sender, EventArgs e)
{
arrMemory[indexer] += double.Parse(box_display.Text);
}
private void btn_mm_Click(object sender, EventArgs e)
{
arrMemory[indexer] -= double.Parse(box_display.Text);
}
}
}
From your designer.cs you've got a Click event handler on the form itself that invokes common_operators, so if that gets fired, it will be an invalid cast since sender will be your CalculatorBase form type and not Button
I am trying to add exception handling with a corresponding message box to a Universal Windows app. I wanted to just use TryParse or Try-Catch, but I can't figure out what the equivalent to a message box is in universal windows apps. I'm not particularly worried about the aesthetics of it now, as long as whatever I do conforms to UWP standards so I don't get into bad habits moving forward.
Here is my C#:
double INCHES = 1;
double FEET = 12;
double YARDS = 36;
double userDist, convertDist, distFrom, distTo;
string unitOfMeasure;
private void convertButton_Click(object sender, RoutedEventArgs e)
{
unitOfMeasure = null;
distFrom = 1;
distTo = 1;
if (inputTextBox.Text != "")
{
userDist = double.Parse(inputTextBox.Text);
if (listBox1.SelectedIndex >= 0 || listBox2.SelectedIndex >= 0)
{
switch (listBox1.SelectedIndex)
{
case 0:
distFrom = INCHES;
unitOfMeasure = " in";
break;
case 1:
distFrom = FEET;
unitOfMeasure = " ft";
break;
case 2:
distFrom = YARDS;
unitOfMeasure = " yd";
break;
}
switch (listBox2.SelectedIndex)
{
case 0:
distTo = INCHES;
unitOfMeasure = " in";
break;
case 1:
distTo = FEET;
unitOfMeasure = " ft";
break;
case 2:
distTo = YARDS;
unitOfMeasure = " yd";
break;
}
convertDist = (userDist * distFrom) / distTo;
outputTextBlock.Text = convertDist.ToString("n2") + unitOfMeasure;
}
else
{
//MessageDialog dialog = new MessageDialog("Please select 'From' and 'To' units.");
}
}
else
{
//MessageDialog dialog = new MessageDialog("Please input a number to convert.");
}
}
private void clearButton_Click(object sender, RoutedEventArgs e)
{
inputTextBox.Text = "";
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
outputTextBlock.Text = "";
distFrom = 1;
distTo = 1;
}
private void exitButton_Click(object sender, RoutedEventArgs e)
{
App.Current.Exit();
}
I think the code you commented out should work if you also add -
await dialog.ShowAsync();
Like Brian said
MessageDialog dialog = new MessageDialog("Please select 'From' and 'To' units.");
await dialog.ShowAsync();
should work. I'd also add that you need to mark convertButton_Click as an async method:
private async void convertButton_Click(object sender, RoutedEventArgs e)
I made this calculator in C# and I have one problem: When I press keyboard something like 1 it gives me incorrect result double number. I don't get the correct result.
Do you know what I am doing wrong,
Thank you very much!
namespace Calculator
{
public partial class Calculator : Form
{
Double value = 0;
String operation = "";
int i = 0;
bool operation_pressed = false;
bool button_dot = false;
OperationClass class1 = new OperationClass();
public Calculator()
{
InitializeComponent();
this.KeyPreview = true;
this.KeyPress += new KeyPressEventHandler(Calculator_KeyPress);
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void Calculator_Load(object sender, EventArgs e)
{
}
private void Calculator_KeyPress(object sender, KeyPressEventArgs e)
{
if ((result.Text == "0") || (operation_pressed))
result.Clear();
switch (e.KeyChar)
{
// key press from 0-9
case (char)48:
case (char)49:
case (char)50:
case (char)51:
case (char)52:
case (char)53:
case (char)54:
case (char)55:
case (char)56:
case (char)57:
e.Handled = true;
result.Text += e.KeyChar.ToString();
break;
}
}
private void button_Click(object sender, EventArgs e)
{
if ((result.Text == "0") || (operation_pressed))
result.Clear();
operation_pressed = false;
Button b = (Button)sender;
result.Text = result.Text + b.Text;
}
private void operator_click(object sender, EventArgs e)
{
Button b = (Button)sender;
operation = b.Text;
value = Double.Parse(result.Text);
operation_pressed = true;
equation.Text = value + " " + operation;
}
private void buttonCE_Click(object sender, EventArgs e)
{
result.Text = "0";
equation.Text = "";
button_dot = false;
}
private void buttonC_Click(object sender, EventArgs e)
{
result.Clear();
value = 0;
}
private void buttonEqual_Click(object sender, EventArgs e)
{
equation.Text = "";
button_dot = false;
operation_pressed = true;
if (operation != "")
result.Text = class1.GetResult(operation, value, result.Text);
else
result.Text = result.Text + "";
}
private void buttonDot_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
if ((!button_dot && !operation_pressed) || result.Text == "0")
result.Text = result.Text + b.Text;
button_dot = true;
}
}
}
You don't need to append keychar in your result.Text (Assuming result is your TextBox item) as you have written in line result.Text += e.KeyChar.ToString();. That's the line which is doubling your input.
Remove it and it'll work as expected.
I'd change it from keypress to KeyUp instead. That way it only fires as soon as the key is released.
Edit: Check out this info: Difference between the KeyDown Event, KeyPress Event and KeyUp Event in Visual Studio
i'm wrtting a code in visual studio c# that converts integers from binary to decimal mode and from decimal mode to binary but i want it to converts numbers with decimal points from decimal mode to binary how can i do this please help me and tell me what modifies i must put in my code
this is my code for the calculator :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace assignment2
{
public partial class Form1 : Form
{
const int asciiDiff = 48;
double num1 = 0, num2 = 0, result = 0;
double fact = 1;
int[] iHexaNumeric = new int[] { 10, 11, 12, 13, 14, 15 };
char[] cHexa = new char[] { 'A', 'B', 'C', 'D', 'E', 'F' };
String a = "";
char op;
bool b = false;
const int base10 = 10;
public Form1()
{
//
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "1";
}
private void buttonTow_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "2";
}
private void buttonThree_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "3";
}
private void buttonFour_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "4";
}
private void buttonFive_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "5";
}
private void buttonSix_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "6";
}
private void buttonSeven_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "7";
}
private void buttonEight_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "8";
}
private void buttonNine_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "9";
}
private void buttonZero_Click(object sender, EventArgs e)
{
a = DisplayResult.Text.ToString();
DisplayResult.Text = a + "0";
}
private void buttonPlus_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '+';
DisplayResult.Text = string.Empty;
}
private void buttonMinus_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '-';
DisplayResult.Text = string.Empty;
}
private void buttonMultipler_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '*';
DisplayResult.Text = string.Empty;
}
private void buttonDivider_Click(object sender, EventArgs e)
{
num1 = Convert.ToDouble(DisplayResult.Text.ToString());
op = '/';
DisplayResult.Text = string.Empty;
}
private void buttonEqual_Click(object sender, EventArgs e)
{
if (DisplayResult.Text == "")
return;
else
{
try
{
num2 = Convert.ToDouble(DisplayResult.Text.ToString());
switch (op)
{
case '+': //suma
result = (num1 + num2);
DisplayResult.Text = result.ToString();
break;
case '-': //resta
result = (num1 - num2);
DisplayResult.Text = result.ToString();
break;
case '*': //multiply
result = (num1 * num2);
DisplayResult.Text = result.ToString();
break;
case '/': //division
if (num2 != 0)
{
result = (num1 / num2);
DisplayResult.Text = result.ToString();
}
else
{
DisplayResult.Text = "Can't divide by 0";
}
break;
}
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error occured. Details: " +
ex.Message);
}
}
}
private void buttonBackSpace_Click(object sender, EventArgs e)
{
try
{
String Value = DisplayResult.Text.ToString();
int temp = Value.Length;
if (temp == 1)
DisplayResult.Text = String.Empty;
else
{
DisplayResult.Text = DisplayResult.Text.Substring(0, temp - 1);
}
}
catch (Exception ex)
{
MessageBox.Show("Unexpected error in buttonBackSpace occured. Details: " +
ex.Message);
}
}
private void buttonClear_Click(object sender, EventArgs e)
{
DisplayResult.Text = String.Empty;
}
private void buttonDecimal_Click(object sender, EventArgs e)
{
if (DisplayResult.Text.Contains("."))
{
return;
}
DisplayResult.Text += ".";
}
private void DecimalRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (DecimalRadioButton.Checked == true)
{
DisplayResult.Text= BaseToDecimal(DisplayResult.Text.ToString(), 2).ToString();
}
buttonTow.Enabled = true;
buttonThree.Enabled = true;
buttonFour.Enabled = true;
buttonFive.Enabled = true;
buttonSix.Enabled = true;
buttonSeven.Enabled = true;
buttonEight.Enabled = true;
buttonNine.Enabled = true;
}
private void BinaryRadioButton_CheckedChanged(object sender, EventArgs e)
{
if (BinaryRadioButton.Checked == true)
{
DisplayResult.Text = DecimalToBase(Convert.ToInt16(DisplayResult.Text.ToString()), 2);
buttonTow.Enabled = false;
buttonThree.Enabled = false;
buttonFour.Enabled = false;
buttonFive.Enabled = false;
buttonSix.Enabled = false;
buttonSeven.Enabled = false;
buttonEight.Enabled = false;
buttonNine.Enabled = false;
}
}
string DecimalToBase(int iDec, int numbase)
{
string strBin = "";
int[] result = new int[32];
int MaxBit = 32;
for (; iDec > 0; iDec /= numbase)
{
int rem = iDec % numbase;
result[--MaxBit] = rem;
}
for (int i = 0; i < result.Length; i++)
if ((int)result.GetValue(i) >= base10)
strBin += cHexa[(int)result.GetValue(i) % base10];
else
strBin += result.GetValue(i);
strBin = strBin.TrimStart(new char[] { '0' });
return strBin;
}
int BaseToDecimal(string sBase, int numbase)
{
int dec = 0;
int b;
int iProduct = 1;
string sHexa = "";
if (numbase > base10)
for (int i = 0; i < cHexa.Length; i++)
sHexa += cHexa.GetValue(i).ToString();
for (int i = sBase.Length - 1; i >= 0; i--, iProduct *= numbase)
{
string sValue = sBase[i].ToString();
if (sValue.IndexOfAny(cHexa) >= 0)
b = iHexaNumeric[sHexa.IndexOf(sBase[i])];
else
b = (int)sBase[i] - asciiDiff;
dec += (b * iProduct);
}
return dec;
}
}
}
When converting a number with a decimal point from decimal to binary, this is what you do: first you take the part before the decimal point and convert it (in the usual way) to binary; and the part after the decimal point you multiply by 2 and see if it is >= 1; if it is not, write 0 and keep multiplying. You are done when it is = 1.00. For example:
2.25 -
You take the 0.25;
0.25 * 2 = 0.50 --> 0,
0.50 * 2 = 1.00 --> 1, and you just read the numbers.
So, 0.25 would be 0.01 (2.25 would be 10.01 binary.)
I cannot for the life of me figure out how to continuously show the input and then output of the numbers for this.
What do you do to store the numbers somewhere and then show them? I've gone in so many circles that I have confused myself to oblivion.
I know what needs to be done but not how or exactly where to do it?
public partial class Form1 : Form
{
char c;
double num1;
double num2;
public Form1()
{
InitializeComponent();
}
private void btn0_Click(object sender, EventArgs e)
{
txtBox.Text += 0;
}
private void btn1_Click(object sender, EventArgs e)
{
txtBox.Text += 1;
}
private void btn2_Click(object sender, EventArgs e)
{
txtBox.Text += 2;
}
private void btn3_Click(object sender, EventArgs e)
{
txtBox.Text += 3;
}
private void btn4_Click(object sender, EventArgs e)
{
txtBox.Text += 4;
}
private void btn5_Click(object sender, EventArgs e)
{
txtBox.Text += 5;
}
private void btn6_Click(object sender, EventArgs e)
{
txtBox.Text += 6;
}
private void btn7_Click(object sender, EventArgs e)
{
txtBox.Text += 7;
}
private void btn8_Click(object sender, EventArgs e)
{
txtBox.Text += 8;
}
private void btn9_Click(object sender, EventArgs e)
{
txtBox.Text += 9;
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (!txtBox.Text.Contains('.'))
txtBox.Text += '.';
}
private void btnAddition_Click(object sender, EventArgs e)
{
c = '+';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnSubtraction_Click(object sender, EventArgs e)
{
c = '-';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnMultiplication_Click(object sender, EventArgs e)
{
c = '*';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnDivision_Click(object sender, EventArgs e)
{
c = '/';
num1 = double.Parse(txtBox.Text);
txtBox.Text = string.Empty;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
}
private void btnEqual_Click(object sender, EventArgs e)
{
num2 = double.Parse(txtBox.Text);
double result;
switch (c)
{
case '+':
result = num1 + num2;
txtBox.Text = result.ToString();
break;
case '-':
result = num1 - num2;
txtBox.Text = result.ToString();
break;
case '/':
if (num2 != 0)
{
result = num1 / num2;
txtBox.Text = result.ToString();
}
else
{
txtBox.Text = "You can't divide by zero... sign up for Math 100 please =)";
}
break;
case '*':
result = num1 * num2;
txtBox.Text = result.ToString();
break;
}
}
}
}
I'll let you wire this up, but here is what I threw together.
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private string op;
private string num1;
private string num2;
private void handleNumberButtonClick(object sender, System.EventArgs e)
{
var num = Convert.ToInt16(((Button)sender).Tag);
if (op == null)
num1 += num;
else
num2 += num;
PrintEquation(num1, op, num2);
}
private void PrintEquation(string first, string oper = null, string second = null, string equals = null, string result = null)
{
txtBox.Text = first + oper + second + equals + result;
}
private void handleOperatorButtonClick(object sender, System.EventArgs e)
{
op = ((Button)sender).Tag.ToString();
PrintEquation(num1, op);
}
private void btnDecimal_Click(object sender, EventArgs e)
{
if (op == null && !num1.Contains(".")) num1 += ".";
if (op != null && !num2.Contains(".")) num2 += ".";
this.PrintEquation(num1, op, num2);
}
private void btnClear_Click(object sender, EventArgs e)
{
txtBox.Clear();
op = null;
num1 = null;
num2 = null;
}
private void btnEqual_Click(object sender, EventArgs e)
{
double result = 0;
var first = Convert.ToDouble(num1);
var second = Convert.ToDouble(num2);
switch (op)
{
case "+":
result = first + second;
break;
case "-":
result = first - second;
break;
case "/":
if (second != 0)
{
result = first / second;
}
else
{
errorLbl.Text = "You can't divide by zero... sign up for Math 100 please =)";
}
break;
case "*":
result = first * second;
break;
}
this.PrintEquation(num1, op, num2, "=", result.ToString());
}
}
To give you a clue on how things go together, this is what the button should look like in the .designer.cs file:
this.btn0.Location = new System.Drawing.Point(12, 60);
this.btn0.Name = "btn0";
this.btn0.Size = new System.Drawing.Size(75, 23);
this.btn0.TabIndex = 1;
this.btn0.Tag = "0";
this.btn0.Text = "btn0";
this.btn0.UseVisualStyleBackColor = true;
this.btn0.Click += new System.EventHandler(this.handleNumberButtonClick);
Notice the .Tag value and the eventhandler.
The Operators should look like this(this is add, notice the tag and the Click Event handler):
this.addButton.Location = new System.Drawing.Point(178, 60);
this.addButton.Name = "addButton";
this.addButton.Size = new System.Drawing.Size(75, 23);
this.addButton.TabIndex = 11;
this.addButton.Tag = "+";
this.addButton.Text = "add";
this.addButton.UseVisualStyleBackColor = true;
this.addButton.Click += new System.EventHandler(this.handleOperatorButtonClick);
And the decimal, like this:
this.button4.Location = new System.Drawing.Point(178, 176);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(75, 23);
this.button4.TabIndex = 15;
this.button4.Tag = ".";
this.button4.Text = "decimal";
this.button4.UseVisualStyleBackColor = true;
this.button4.Click += new System.EventHandler(this.btnDecimal_Click);
Oh, and throw this in your clear button definition
this.button5.Click += new System.EventHandler(this.btnClear_Click);
Special thanks to #Mark Hall and #Martin James for their insights