C# School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

Welcome to Dream.In.Code
Become a C# Expert!

Join 307,097 C# Programmers for FREE! Get instant access to thousands of C# experts, tutorials, code snippets, and more! There are 2,044 people online right now. Registration is fast and FREE... Join Now!




Basic Calculator in C#

 
Reply to this topicStart new topic

> Basic Calculator in C#

PsychoCoder
Group Icon



post 9 Sep, 2007 - 07:36 PM
Post #1


In this tutoral, Basic Calculator in C#, we will look at creating a basic calculator. The calculator will have the following functionality:
  • Addition
  • Subtraction
  • Division
  • Multiplication
  • Square Root
  • Exponents (Power Of)
  • Clear Entry
  • Clear All
There will be a 2nd tutorial that will cover some more advanced features such as
  • Adding a number to memory
  • Removing a number from memory
  • Calculating with a number in memory
  • Entering numbers by typing
The first thing you need to do is create a new project in Visual Studio (or Visual Basic Express Edition if thats what you use). Once you have created your new project you need to create your user interface, your user interface should look like this:



Your user interface will consist of
  • Buttons 0 through 9
  • Buttons for
    • Addition
    • Subtraction
    • Division
    • Multiplication
    • Exponents (x^)
    • Inverse (1/x)
    • Square Root (sqrt)
  • Decimal
  • Equals
  • Backspace
  • CE (Clear Entry)
  • C (Clear All)
  • ReadOnly TextBox for input (Make sure TabStop is also set to False)
How you setup your user interface is up to you, but remember people are used to a calculator looking a certain way so you may wish to follow my example. In this tutorial I will show you how to code two of the number buttons (since all 10 are the same except the zero button), how to code the calculations buttons, the clear buttons and the backspace buttons. For two of the buttons we will need to use built-in math functions in the .Net Framework:For the record there are many more members of the System.Math Class located at the online MSDN.

Now, in our calculator we need some Global variables to hold different items and states in our calculator, such as which calculation are we performing, does the input area already have a decimal, whether we can enter values into the input area and to hold values while we perform calculations. Add the following code to the top of your code, this is the global variables we need in our calculator:

CODE

//variables to hold operands
private double valHolder1;
private double valHolder2;
//Varible to hold temporary values
private double tmpValue;
//True if "." is use else false
private bool hasDecimal = false;
private bool inputStatus = true;
//variable to hold Operater
private string calcFunc;


These variables will be used through out our program thats why they're globals. Now, before any calculations can be done, the user needs to be able to enter numbers into the input box, so lets take a look at how to do that. Since all the number keys in the calculator are the same (except the 0 (zero) key, we'll conver that in a minute) I will code one of the buttons, then you can do the rest. Lets take a look at the number one key:

CODE

private void cmd1_Click(object sender, System.EventArgs e)
{
    //Check the inputStatus
    if (inputStatus)
    {
        //Its True
        //Append values to the value
        //in the input box
        txtInput.Text += cmd1.Text;
    }
    else
    {
        //Value is False
        //Set the value to the value of the button
        txtInput.Text = cmd1.Text;
        //Toggle inputStatus to True
        inputStatus = true;
    }
}


When a user clicks a number button (in this case the number one button) we check the status of the inputStatus flag. If its true then we know we can just append the next value to the end of whats currently in the input box, otherwise we just enter the number into the input box. All the remaining numbers, as stated before, follow this procedure. The zero button slightly different as we don't want the user to be able to enter zero as the first number (this is covered more in the decimal button functionality). So lets take a look at how we code the zero button:

CODE

private void cmd0_Click(object sender, System.EventArgs e)
{
    //Check the input status
    if (inputStatus)
    {
        //If true
        //Now check to make sure our
        //input box has a value
        if (txtInput.Text.Length >= 1)
        {
            //Add our zero
            txtInput.Text += cmd0.Text;
        }
    }
}


First we check the status of the inputStatus flag, if its true we know we can enter a number in the box. Here we do a second check, we make sure the length of the text in the input box is at least 1 (it has a value), if so we enter the zero into the input box.

For adding a decimal to our input box we need to first make sure our input box doesn't already contain one, for this we use the hasDecimal global (boolean) variable, then we need to make sure our input box has a value (don't want the user to be able to enter a decimal as the first value). Then we make sure the value in the input area isn't 0 (zero), this we will handle later.

If all those are true then we enter the decimal then toggle the hasDecimal to True, so the user cant enter a 2nd one. Now, if the input area doesn't have a value, we enter 0., as we assume the user is wanting to work with a decimal value such as 0.5. Lets take a look at the procedure for doing this:

CODE

private void cmdDecimal_Click(object sender, System.EventArgs e)
{
    //Check for input status (we want true)
    if (inputStatus)
    {
        //Check if it already has a decimal (if it does then do nothing)
        if (!hasDecimal)
        {
            //Check to make sure the length is > than 1
            //Dont want user to add decimal as first character
            if (txtInput.Text.Length != 0)
            {
                //Make sure 0 isnt the first number
                if (txtInput.Text != "0")
                {
                    //It met all our requirements so add the zero
                    txtInput.Text += cmdDecimal.Text;
                    //Toggle the flag to true (only 1 decimal per calculation)
                    hasDecimal = true;
                }
            }
            else
            {
                //Since the length isnt > 1
                //make the text 0.
                txtInput.Text = "0.";
            }
        }
    }
}


As you can see, we check all the items mentioned above, if they're True we add the decimal, otherwise we add 0. to the input area.

The first calculation we will look at is addition. The first thing we do here is to make sure the input box has a value (Length > 1). If it does then we check the calcFunc value. The calcFunction variable will be used to tell our CalculateTotals procedure which calculation to perform. Here, if the value is empty (String.Empty) we assign the value of our input box to a variable, valHolder1, which will hold the first part of all calculations, then clear out the input box so the user can enter a 2nd number.

If the calcFunc variable isnt empty then we call our CalculateTotals procedure to display a total to the user. We then assign the value of Add to our variable for the next turn through, then we toggle the hasDecimal flag to False. Now lets take a look at how we accomplished this:

CODE

private void cmdAdd_Click(object sender, System.EventArgs e)
{
    //Make sure out input box has a value
    if (txtInput.Text.Length != 0)
    {
        //Check the value of our function flag
        if (calcFunc == string.Empty)
        {
            //Flag is empty
            //Assign the value in our input
            //box to our holder
            valHolder1 = System.Double.Parse(txtInput.Text);
            //Empty the input box
            txtInput.Text = string.Empty;
        }
        else
        {
            //Flag isnt empty
            //Call our calculate totals method
            CalculateTotals();
        }
        //Assign a value to our calc function flag
        calcFunc = "Add";
        //Toggle the decimal flag
        hasDecimal = false;
    }
}


Believe it or not, all the other basic calculation buttons are the same as the Add button, with the exception of what we set calcFunc to. In the other buttons we set this variable to the calculation we want to perform, Subtract,
Divide, Multiply, and so on, so there really isn't a reason to show how that is done since we did the Add button and the others are the same.

Even though they are the same I'll show the functionality of one more calculation button. This time we will look at the code for the subtraction button. The first thing we do here is to make sure the input box has a value (Length > 1). If it does then we check the calcFunc value. The calcFunction variable will be used to tell our CalculateTotals procedure which calculation to perform. Here, if the value is empty (String.Empty) we assign the value of our input box to a variable, valHolder1, which will hold the first part of all calculations, then clear out the input box so the user can enter a 2nd number.

If our calcFunction isnt empty then we call our CalculateTotals method to perform the calculations. We then assign the value of Subtract to our calcFunc variable so the calculations method will know which calculation to perform. The code for the subtraction button looks like this:

CODE

private void cmdSubtract_Click(object sender, System.EventArgs e)
{
    //Make sure the input box has a value
    if (txtInput.Text.Length != 0)
    {
        //Check the valueof our calculate function flag
        if (calcFunc == string.Empty)
        {
            //Flag is empty
            //Assign the value of our input
            //box to our holder
            valHolder1 = System.Double.Parse(txtInput.Text);
            //Empty the input box
            txtInput.Text = string.Empty;
        }
        else
        {
            //Flag isnt empty
            //Call our calculate totals method
            CalculateTotals();
        }
        //assign a value to our
        //calculate function flag
        calcFunc = "Subtract";
        //Toggle the decimal flag
        hasDecimal = false;
    }
}


Thats how the normal calculation buttons are coded. Now lets say you want to give the user the option to calculate Exponents, 4^2 for example. To code this button you need a couple of checks before doing anything. First we need to check and make sure the input area has a value, if it does then we check to see the value of the calcFunc variable.

If this is empty, we then convert the value of the input area to a Double and assign it to the valHolder1 variable to hold on to, this will be used for the calculations in the CalculateTotals procedure and empth the value from the input area.. If its not empty we directly call the CalculateTotals function as this means the user has already entered 2 numbers.

We then assign the value of PowerOf to our calcFunc variable, this will tell CalculateTotals what calculation to perform, and toggle the hasDecimal flag to False. Lets take a look at how we accomplished all of this:

CODE

private void cmdPowerOf_Click(object sender, System.EventArgs e)
{
    //Make sure the input box has a value
    if (txtInput.Text.Length != 0)
    {
        //Check if the calcFunc flag is empty
        if (calcFunc == string.Empty)
        {
            //Assign the value of the input box to our variable
            valHolder1 = System.Double.Parse(txtInput.Text);
            //Empty the input box
            //So the user can enter the power of value
            txtInput.Text = string.Empty;
        }
        else
        {
            //Call the calculate totals method
            CalculateTotals();
        }
        //Assign our flag the value of "PowerOf"
        calcFunc = "PowerOf";
        //Reset the decimal flag
        hasDecimal = false;
    }
}


Doing a Square Root is somewhat different as it doesn't take 2 values, just the number you want the square root of, so some of the checking required in the other calculations isn't required here. For a Square Root we first check to ensure the input area has a value. If it does have a value we assign the value of the input area, converted to a Double, to our tmpValue variable.

Once we have the value, we call the System.Math.Sqrt Method to perform the calculations on the tmpValue variable. Once this is complete we assign the resulting value to our input area, then toggle the hasDecimal flag to False. Lets take a look at how this is done:

The Equals button is quite simple. Here, we first check to make sure our input area has a value and that our valHolder1 variable isn't a zero (Divide by 0 is a bad thing). If both of these are true we call the CalculateTotals procedure to perform our calculations based on the value of the calcFunc flag. We then clear the value of calcFunc and toggle the hasDecimal flag to False. This is done like this:

CODE

private void cmdSqrRoot_Click(object sender, System.EventArgs e)
{
    //Make sure the input box has a value
    if (txtInput.Text.Length != 0)
    {
        //Assign our variable the value in the input box
        tmpValue = System.Double.Parse(txtInput.Text);
        //Perform the square root
        tmpValue = System.Math.Sqrt(tmpValue);
        //Display the results in the input box
        txtInput.Text =  tmpValue.ToString();
        //Clear the decimal flag
        hasDecimal = false;
    }
}


In the last 2 buttons we have looked at how you use the two System.Math Members I mentioned earlier, pretty simple isnt it.

We have 3 more buttons to look at before we look at the CalculateTotals procedure. First we'll look at the backspace button.For the backspace, first we need to make sure the input are has a value. If it does then we retrieve the next to last character and see if its a decimal, if it is we toggle the hasDecimal flag to False. Next we create an Integer variable (loc) to hold the length of the contents in the input area. From there we use Remove, along with loc to remove the last character of the string for each time the user clicks the backspace button.

CODE

private void cmdBackspace_Click(object sender, System.EventArgs e)
{
    //Declare locals needed
    string str;
    int loc;
    //Make sure the text length is > 1
    if (txtInput.Text.Length > 0)
    {
        //Get the next to last character
        str = txtInput.Text.Substring(txtInput.Text.Length - 1);
        //Check if its a decimal
        if (str == ".")
        {
            //If it is toggle the hasDecimal flag
            hasDecimal = false;
        }
        //Get the length of the string
        loc = txtInput.Text.Length;
        //Remove the last character, incrementing by 1
        txtInput.Text = txtInput.Text.Remove(loc - 1, 1);
    }
}



The last 2 buttons I'm going to demonstrate are the CE (Clear entry) and C (Clear all) buttons. These are very simple. First the clear entry button. What we do here is set the value in the input area to empty (String.Empty), and the hasDecimal flag to false.

CODE

private void cmdClearEntry_Click(object sender, System.EventArgs e)
{
    //Empty the input box
    txtInput.Text = string.Empty;
    //Toggle the decimal flag
    hasDecimal = false;
}


The clear all button required a bit more code as we do more with this button. Here we set our 2 holder variables, valHolder1 and valHolder2 to 0 (zero), we then set the calcFunc flag to String.Empty and the hasDecimal flag to False, like this:

CODE

private void cmdClearAll_Click(object sender, System.EventArgs e)
{
    //Empty the text in the input box
    txtInput.Text = string.Empty;
    //Clear out both temp values
    valHolder1 = 0;
    valHolder2 = 0;
    //Set the calc switch to empty
    calcFunc = string.Empty;
    //Toggle the hasDecimal flag
    hasDecimal = false;
}


Those are the buttons you need for a Basic calculator. The final thing we're going to look at is the procedure that actually does the calculations, CalculateTotals. Here the first thing we do is set our variable valHolder2 to the current value of the input area.

We then do a switch(calcFunc) on the value of calcFunc so we know which calculations to perform. We perform our calculations (add, subtract, divide, multiply, exponent, etc) and set the results to the input area so the user can see their results. Finally we set the inputEntry flag to False. This is what this procedure looks like:

CODE

private void CalculateTotals()
{
    valHolder2 = System.Double.Parse(txtInput.Text);
    //determine which calculation we're going to execute
    //by checking the value of calcFunc
    switch (calcFunc)
    {
            //addition
        case "Add":
            valHolder1 = valHolder1 + valHolder2;
            break;
            //subtraction
        case "Subtract":
            valHolder1 = valHolder1 - valHolder2;
            break;
            //division
        case "Divide":
            valHolder1 = valHolder1 / valHolder2;
            break;
            //multiplication
        case "Multiply":
            valHolder1 = valHolder1 * valHolder2;
            break;
            //exponents (power of)
        case "PowerOf":
            valHolder1 = System.Math.Pow(valHolder1, valHolder2);
            break;
    }
    //set our input area to the value of the calculation
    txtInput.Text = valHolder1.ToString();
    inputStatus = false;
}


NOTE: For the Exponents (Power Of) we use the System.Math.Pow Method for calculating the value.

There are two more buttons in this calculator that we didn't cover, basically due to the length of the tutorial. Those buttons are included in the sample project I'm attaching to this tutorial.

Thats it, thats how you create a basic calculator in VB.Net. I hope you find this tutorial helpful. I am including the project file with this tutorial, but remember this solution is under the GNU GENERAL PUBLIC LICENSE so you may not remove the header from the files or turn this project in as your homework assignment.

I know I am forced to go with the honor system in this, but if you do just turn this in as your assignment not only will you be cheating, but you will learn nothing, and subsequently wont know enough to become a programmer once you get out of school.

I will be doing a 2nd part to this tutorial where I look at adding more advanced functionality to this calculator, such
as adding a number to memory, removing a number from memory, calculations with a number in memory and more.

Thank you for reading!

Attached File  PC_Calculator_CSharp.zip ( 120.99k ) Number of downloads: 3982
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!

Allen.Brumley
*



post 25 Jan, 2008 - 07:50 AM
Post #2
QUOTE(PsychoCoder @ 9 Sep, 2007 - 08:36 PM) *

In this tutoral, Basic Calculator in C#, we will look at creating a basic calculator. The calculator will have the following functionality:

The Equals button is quite simple. Here, we first check to make sure our input area has a value and that our valHolder1 variable isn't a zero (Divide by 0 is a bad thing). If both of these are true we call the CalculateTotals procedure to perform our calculations based on the value of the calcFunc flag. We then clear the value of calcFunc and toggle the hasDecimal flag to False. This is done like this:

CODE

private void cmdSqrRoot_Click(object sender, System.EventArgs e)
{
    //Make sure the input box has a value
    if (txtInput.Text.Length != 0)
    {
        //Assign our variable the value in the input box
        tmpValue = System.Double.Parse(txtInput.Text);
        //Perform the square root
        tmpValue = System.Math.Sqrt(tmpValue);
        //Display the results in the input box
        txtInput.Text =  tmpValue.ToString();
        //Clear the decimal flag
        hasDecimal = false;
    }
}



FYI This was supposed to be the equals example but it is Square Root.

I worked through it with the instructions anyways but thought you might like to know.

Thanks

Allen
Go to the top of the page
+Quote Post

PsychoCoder
Group Icon



post 25 Jan, 2008 - 07:53 AM
Post #3
@Allen.Brumley: Thanks, Ill get to fixing that
Go to the top of the page
+Quote Post

MeghaRazdan
*



post 31 Jan, 2008 - 04:46 AM
Post #4
QUOTE(Allen.Brumley @ 25 Jan, 2008 - 08:50 AM) *

QUOTE(PsychoCoder @ 9 Sep, 2007 - 08:36 PM) *

In this tutoral, Basic Calculator in C#, we will look at creating a basic calculator. The calculator will have the following functionality:

The Equals button is quite simple. Here, we first check to make sure our input area has a value and that our valHolder1 variable isn't a zero (Divide by 0 is a bad thing). If both of these are true we call the CalculateTotals procedure to perform our calculations based on the value of the calcFunc flag. We then clear the value of calcFunc and toggle the hasDecimal flag to False. This is done like this:

CODE

private void cmdSqrRoot_Click(object sender, System.EventArgs e)
{
    //Make sure the input box has a value
    if (txtInput.Text.Length != 0)
    {
        //Assign our variable the value in the input box
        tmpValue = System.Double.Parse(txtInput.Text);
        //Perform the square root
        tmpValue = System.Math.Sqrt(tmpValue);
        //Display the results in the input box
        txtInput.Text =  tmpValue.ToString();
        //Clear the decimal flag
        hasDecimal = false;
    }
}



FYI This was supposed to be the equals example but it is Square Root.

I worked through it with the instructions anyways but thought you might like to know.

Thanks

Allen


hi Allen.Can you please give me the code for the equals button.
Go to the top of the page
+Quote Post

PsychoCoder
Group Icon



post 31 Jan, 2008 - 07:49 AM
Post #5
This is the code for the equals button, which is listed at the end of the tutorial:


CODE

private void CalculateTotals()
{
    valHolder2 = System.Double.Parse(txtInput.Text);
    //determine which calculation we're going to execute
    //by checking the value of calcFunc
    switch (calcFunc)
    {
            //addition
        case "Add":
            valHolder1 = valHolder1 + valHolder2;
            break;
            //subtraction
        case "Subtract":
            valHolder1 = valHolder1 - valHolder2;
            break;
            //division
        case "Divide":
            valHolder1 = valHolder1 / valHolder2;
            break;
            //multiplication
        case "Multiply":
            valHolder1 = valHolder1 * valHolder2;
            break;
            //exponents (power of)
        case "PowerOf":
            valHolder1 = System.Math.Pow(valHolder1, valHolder2);
            break;
    }
    //set our input area to the value of the calculation
    txtInput.Text = valHolder1.ToString();
    inputStatus = false;
}
Go to the top of the page
+Quote Post

mandy2010
*



post 17 May, 2008 - 01:30 AM
Post #6
you can also have some buttons for sin theta and cos theta

thaaanx!!
Go to the top of the page
+Quote Post

WorkingC#
*



post 21 Oct, 2008 - 07:20 PM
Post #7
QUOTE(PsychoCoder @ 31 Jan, 2008 - 08:49 AM) *

This is the code for the equals button, which is listed at the end of the tutorial:


CODE

private void CalculateTotals()
{
    valHolder2 = System.Double.Parse(txtInput.Text);
    //determine which calculation we're going to execute
    //by checking the value of calcFunc
    switch (calcFunc)
    {
            //addition
        case "Add":
            valHolder1 = valHolder1 + valHolder2;
            break;
            //subtraction
        case "Subtract":
            valHolder1 = valHolder1 - valHolder2;
            break;
            //division
        case "Divide":
            valHolder1 = valHolder1 / valHolder2;
            break;
            //multiplication
        case "Multiply":
            valHolder1 = valHolder1 * valHolder2;
            break;
            //exponents (power of)
        case "PowerOf":
            valHolder1 = System.Math.Pow(valHolder1, valHolder2);
            break;
    }
    //set our input area to the value of the calculation
    txtInput.Text = valHolder1.ToString();
    inputStatus = false;
}



So what if we had to place CalculateTotals() in a separate class? I have tried but it gives me errors since I cannot access the variables and textbox created in my forms class. Any help would be great! icon_up.gif
Go to the top of the page
+Quote Post

Nomantheone
*



post 15 Apr, 2009 - 09:57 AM
Post #8
Thanks.
Go to the top of the page
+Quote Post

Elliander
*



post 15 May, 2009 - 05:51 PM
Post #9
The Tutorial was overall very helpful, but there were a few problems with the code.

As it is, it actually allowed the user to enter two decimal points. This was fixed easily by adding another:

hasDecimal = true;

at the very end of the decimal code.

It also had a Fatal Error. If the user enters a number, then doesn't enter a second number, it crashes on pressing "=" because there is no value stored valHolder2. It would run better if by default it had a value of 0 like windows calculator uses so if the user doesn't enter a second number it can't crash anything.

I ran the program beside windows calculator to see the difference. One major difference was quickly seen.

For example, in adding 1 + 3 = 4, in windows Calculator, if you press "=" again, it would then say "7" then "10" then "13" etc. But in this program it would say "8" then "16" then "32" then "64" etc.

In other words, Windows Calculator would take the value of the second number entered and use that each time "=" is pressed but your code acts as a doubler. I wouldn't mind seeing how it would work to make it run like Windows Calculator.

Edit:

Another serious problem with this code is that powerof doesn't really work at all. If the answer would be less than 0, it displays nothing, and if the answer would be greater than 0, it displays 0.

It seems to be impossible to do 999 times .001 times .001 because of the way the decimal points are written. when I try, I get 999 times .001 times 1. If I try to press "=" after it and try again, same thing. So certain forms of long math are pretty much impossible as it is written.

The code is also unable to display more than 15 characters. Which can be a real problem. Sometimes it cuts off the end of so many digits, other time it does this:

9999999991 times 9999999991 = 99999999820000000081 , in windows calculator, but = 9.999999982E+19 in your code. (exactly 15 characters) even though the display area and textbox settings should allow for more. The average user won't know how to read that.



This post has been edited by Elliander: 15 May, 2009 - 06:23 PM
Go to the top of the page
+Quote Post

source144
*



post 6 Jun, 2009 - 10:00 PM
Post #10
this isn't a console application??
can you make a tutorial for a console application??
Go to the top of the page
+Quote Post

Irish18
*



post 15 Jun, 2009 - 02:00 PM
Post #11
QUOTE

CODE

private void cmd1_Click(object sender, System.EventArgs e)
{
    //Check the inputStatus
    if (inputStatus)
    {
        //Its True
        //Append values to the value
        //in the input box
        txtInput.Text += cmd1.Text;
    }
    else
    {
        //Value is False
        //Set the value to the value of the button
        txtInput.Text = cmd1.Text;
        //Toggle inputStatus to True
        inputStatus = true;
    }
}



When I write this part of the code the 'txtInput.Text' and 'cmd1.Text' say ; ''The name 'txtInput.Text' does no exsist in the current context''

I can't figure out were i've gone wrong cause ive followed all the code before that to the letter
Go to the top of the page
+Quote Post

papuccino1
Group Icon



post 15 Jun, 2009 - 03:15 PM
Post #12
Irish18, you probably DO NOT have a TextBox called "txtInput" on your form. Triple-check for that. I'm 999% percent sure that's the problem.
Go to the top of the page
+Quote Post

Irish18
*



post 16 Jun, 2009 - 06:26 AM
Post #13
QUOTE(papuccino1 @ 15 Jun, 2009 - 03:15 PM) *

Irish18, you probably DO NOT have a TextBox called "txtInput" on your form. Triple-check for that. I'm 999% percent sure that's the problem.


Gutted, i knew id made some stupid rookie mistake. sad.gif

Thanks!
Go to the top of the page
+Quote Post

Irish18
*



post 16 Jun, 2009 - 06:40 AM
Post #14
QUOTE(papuccino1 @ 15 Jun, 2009 - 03:15 PM) *

Irish18, you probably DO NOT have a TextBox called "txtInput" on your form. Triple-check for that. I'm 999% percent sure that's the problem.


Gyargh, I found the name of my TextBox, it was called 'textBox1'; so i put that infront of '.Text' and its giving the same error message

This is what i have so far;

CODE


public class Program
    {
        // variables to hold operands
        private double valHolder1;
        private double valHolder2;
        
        // variable to hold temporary values
        private double tmpValue;

        // True if '.' is use else false
        private bool hasDecimal = false;
        private bool inputStatus = true;

        // variable to hold Operator
        private string calcFunc;
      
        [STAThread]
        public void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button1.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button1.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }



Go to the top of the page
+Quote Post

lesPaul456
Group Icon



post 17 Jun, 2009 - 08:52 AM
Post #15
QUOTE(Irish18 @ 16 Jun, 2009 - 08:40 AM) *

QUOTE(papuccino1 @ 15 Jun, 2009 - 03:15 PM) *

Irish18, you probably DO NOT have a TextBox called "txtInput" on your form. Triple-check for that. I'm 999% percent sure that's the problem.


Gyargh, I found the name of my TextBox, it was called 'textBox1'; so i put that infront of '.Text' and its giving the same error message

This is what i have so far;

CODE


public class Program
    {
        // variables to hold operands
        private double valHolder1;
        private double valHolder2;
        
        // variable to hold temporary values
        private double tmpValue;

        // True if '.' is use else false
        private bool hasDecimal = false;
        private bool inputStatus = true;

        // variable to hold Operator
        private string calcFunc;
      
        [STAThread]
        public void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button1.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button1.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }




In the code you pasted, the button1 click event looks like it's in the "Program" class. If that's right, then there's your problem. This method should be in the "Form1" class.
Go to the top of the page
+Quote Post

Irish18
*



post 24 Jun, 2009 - 08:01 AM
Post #16
Now that I've finished my Calculator, its not putting anything in the input box when i press the buttons.

I'm pressing Ctrl+F5 to run it and its coming up, with all the buttons in place but nothing happens when i press them.
Positive ive followed the code right to the letter.
But ive probably made another rookie mistake:

CODE


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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        // variables to hold operands
        private double valHolder1;
        private double valHolder2;

        // variable to hold temporary values
        private double tmpValue;

        // True if '.' is use else false
        private bool hasDecimal = false;
        private bool inputStatus = true;

        // variable to hold Operator
        private string calcFunc;

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private void button1_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button1.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button1.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }

        //Due to a mix up when creating the form, button4 is actually number 2
        private void button4_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button4.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button4.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }

        //and button6 is nimber 3
        private void button6_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button6.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button6.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }

        // button32 is number 4
        private void button32_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button32.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button32.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }

        // button7 is number 5
        private void button7_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button7.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button7.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }

        // button5 is number6
        private void button5_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button5.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button5.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }

        // button8 is number 7
        private void button8_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button8.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button8.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }

        // button3 is number 8
        private void button3_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button3.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button3.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }


        private void button9_Click(object sender, System.EventArgs e)
        {
            //Check the inputStatus
            if (inputStatus)
            {
                //Its True
                //Append values to the value
                //in the input box
                textBox1.Text += button9.Text;
            }
            else
            {
                //Value is False
                //Set the value to the value of the button
                textBox1.Text = button9.Text;
                //Toggle inputStatus to True
                inputStatus = true;
            }
        }

        // The number zero has slightly different code to the other
        // 9 numbers as we don't want to be able to write a zero as
        // the first number.
        private void button10_Click(object sender, System.EventArgs e)
        {
            //Check the input Status
            if (inputStatus)
            {
                //If True
                //Now check to make sure the
                //input Box has a value
                if (textBox1.Text.Length >= 1)
                {
                    //Add our zero
                    textBox1.Text += button10.Text;
                }
            }
        }

        private void button11_Click(object sender, System.EventArgs e)
        {
            //Check the input status
            if (inputStatus)
            {
                //Check that it already has a decimal, if it does: do nothing.
                if (!hasDecimal)
                {
                    //Check to make sure the length is > 1
                    //Dont want user to add decimal as first charachter
                    if (textBox1.Text.Length != 0)
                    {
                        //make sure zero isnt the first number
                        if (textBox1.Text != "0")
                        {
                            //It met all requirements so add the zero
                            textBox1.Text += button11.Text;
                            //Toggle the flag to true (only one decimal per calculation)
                            hasDecimal = true;
                        }
                    }
                    else
                    {
                        //Since the length isnt > 1
                        //make the text = 0.
                        textBox1.Text = "0.";
                    }
                }
            }
        }

        private void button16_Click(object sender, System.EventArgs e)
        {
            //Make sure input box has a value
            if (textBox1.Text.Length != 0)
            {
                //Check the values of the function flag
                if (calcFunc == string.Empty)
                {
                    //Flag is empty
                    //Assign the value in the input
                    //box to our holder
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    //Empty the input box
                    textBox1.Text = string.Empty;
                }
                else
                {
                    //Flag isnt empty
                    //Call the CalculateTotals method
                    CalculateTotals();
                }
                //Assign a value to the calc function flag
                calcFunc = "Add";
                //Toggle the decimal flag
                hasDecimal = false;
            }
        }

        private void button17_Click(object sender, System.EventArgs e)
        {
            //Make sure the input box has a value
            if(textBox1.Text.Length != 0)
            {
                //Check the value of the calculate function flag
                if (calcFunc == string.Empty)
                {
                    //Flag is empty
                    //Assign the value
                    //box to the holder
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    //Empty the input box
                    textBox1.Text = string.Empty;
                }
                else
                {
                    //Flag isnt empty
                    //Call the calculate totals method
                    CalculateTotals();
                }
                //assign a value to the
                //calculate function flag
                calcFunc = "Subtract";
                //Toggle the decimal flag
                hasDecimal = false;
            }
        }

        private void button18_Click(object sender, System.EventArgs e)
        {
            //Make sure the input box has a value
            if (textBox1.Text.Length != 0)
            {
                //Check the value of the calculate function flag
                if (calcFunc == string.Empty)
                {
                    //Flag is empty
                    //Assign the value
                    //box to the holder
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    //Empty the input box
                    textBox1.Text = string.Empty;
                }
                else
                {
                    //Flag isnt empty
                    //Call the calculate totals method
                    CalculateTotals();
                }
                //assign a value to the
                //calculate function flag
                calcFunc = "Multiply";
                //Toggle the decimal flag
                hasDecimal = false;
            }
        }

        private void button19_Click(object sender, System.EventArgs e)
        {
            //Make sure the input box has a value
            if (textBox1.Text.Length != 0)
            {
                //Check the value of the calculate function flag
                if (calcFunc == string.Empty)
                {
                    //Flag is empty
                    //Assign the value
                    //box to the holder
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    //Empty the input box
                    textBox1.Text = string.Empty;
                }
                else
                {
                    //Flag isnt empty
                    //Call the calculate totals method
                    CalculateTotals();
                }
                //assign a value to the
                //calculate function flag
                calcFunc = "Divide";
                //Toggle the decimal flag
                hasDecimal = false;
            }
        }

        private void button20_Click(object sender, System.EventArgs e)
        {
            //Make sure the input biox has a value
            if (textBox1.Text.Length != 0)
            {
                //Check the value of the calculate function flag
                if (calcFunc == string.Empty)
                {
                    //Flag is empty
                    //Assign the value
                    //box to the holder
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    //Empty the input box
                    textBox1.Text = string.Empty;
                }
                else
                {
                    //Flag isnt empty
                    //Call the calculate totals method
                    CalculateTotals();
                }
                //assign a value to the
                //calculate function flag
                calcFunc = "PowerOf";
                //Toggle the decimal flag
                hasDecimal = false;
            }
        }

        private void button22_Click(object sender, System.EventArgs e)
        {
            //Make sure the input has a value
            if (textBox1.Text.Length != 0)
            {
                //Assign the variable the value in the input box
                tmpValue = System.Double.Parse(textBox1.Text);
                //Perform the square root
                tmpValue = System.Math.Sqrt(tmpValue);
                //Display the results in the input box
                textBox1.Text = tmpValue.ToString();
                //Clear the deciaml flag
                hasDecimal = false;
            }
        }

        private void button15_Click(object sender, System.EventArgs e)
        {
            //declare locals needed
            string str;
            int loc;
            //Make sure the input has a value
            if (textBox1.Text.Length != 0)
            {
                //get the next to last charachter
                str = textBox1.Text.Substring(textBox1.Text.Length - 1);
                // Check if it has a decimal
                if (str == ".")
                {
                    //Toggle the hasDecimal flag
                    hasDecimal = false;
                }
                //Get the length of the string
                loc = textBox1.Text.Length;
                //Remove the last charachter of the string
                textBox1.Text = textBox1.Text.Remove(loc - 1, 1);
            }
        }

        private void button13_Click(object sender, System.EventArgs e)
        {
            //Empty the input box
            textBox1.Text = string.Empty;
            //Toggle the deciaml flag
            hasDecimal = false;
        }

        private void button14_Click(object sender, System.EventArgs e)
        {
            //clear the input box
            textBox1.Text = string.Empty;
            //Set the valHolders to 0
            valHolder1 = 0;
            valHolder2 = 0;
            //Set the calcFunc switch to empty
            calcFunc = string.Empty;
            //Toggle the decimal flag;
            hasDecimal = false;
        }

        private void CalculateTotals()
        {
            valHolder2 = System.Double.Parse(textBox1.Text);
            //determine which calculation to execute
            //by checking the value of calcFunc
            switch (calcFunc)
            {
                //addition
                case "Add":
                    valHolder1 = valHolder1 + valHolder2;
                    break;

                //subtraction
                case "Subtract":
                    valHolder1 = valHolder1 - valHolder2;
                    break;

                //multiply
                case "Multiply":
                    valHolder1 = valHolder1 * valHolder2;
                    break;

                //division
                case "Divide":
                    valHolder1 = valHolder1 / valHolder2;
                    break;

                //Power of
                case "PowerOf":
                    valHolder1 = System.Math.Pow(valHolder1, valHolder2);
                    break;
            }
            //set our input area to the value of the calculation
            textBox1.Text = valHolder1.ToString();
            inputStatus = false;
        }
    }
}



Gyah.
Go to the top of the page
+Quote Post

pareidolia
*



post 25 Sep, 2009 - 10:46 PM
Post #17
Just wanted to let you know that the code for the square root button is still in Visual Basic. I'm sure people can figure it out but thought maybe you would want to fix it.

Edit: Kept reading and saw it below it. Shouldn't have jumped to conclusions. tongue.gif

This post has been edited by pareidolia: 25 Sep, 2009 - 10:53 PM
Go to the top of the page
+Quote Post

Kratos61
*



post 31 Oct, 2009 - 07:05 PM
Post #18
whenever i put in the parts of the code that include the CalculateTotals method I keep getting an error message saying " The name "CalculateTotals" does not exist in the current context" whats happening?
my code so far is :
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 Calculator
{
public partial class frmCalculator : Form
{
//variables to hold operands
private double valHolder1;
private double valHolder2;
//Varible to hold temporary values
private double tmpValue;
//True if "." is use else false
private bool hasDecimal = false;
private bool inputStatus = true;
//variable to hold Operater
private string calcFunc;

public frmCalculator()
{
InitializeComponent();
}


private void frmCalculator_Load(object sender, EventArgs e)
{

}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}

private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(" This is a Calculator. This calculator can do all the functions of a basic calculator and then some.", "about");
}

private void howToUseThisCalculatorToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Click the numbers you need and they will appear on the number bar. Zero cannot be selected as the first number. n! is a factorial. √ is a square root sign. ^ is for exponents. GFC stands for Greatest common factor. MS (Memory save) is to add a number to the memory, MR (Memory recall) is used to recall that number, M+ (Memory Addition) is used to add a number to your saved number, and MC (Memory Clear) clears the number saved in the memory.", "How to use the calculator");
}

private void btnOne_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnOne.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnOne.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnTwo_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnTwo.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnTwo.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnThree_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnThree.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnThree.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnFour_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnFour.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnFour.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnFive_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnFive.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnFive.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnSix_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnSix.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnSix.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnSeven_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnSeven.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnSeven.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnEight_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnEight.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnEight.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnNine_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnNine.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnNine.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnZero_Click(object sender, EventArgs e)
{
//Check the input status
if (inputStatus)
{
//If true
//Now check to make sure our
//input box has a value
if (txtNumberBar.Text.Length >= 1)
{
//Add our zero
txtNumberBar.Text += btnZero.Text;

}

}
}

private void btnDecimal_Click(object sender, EventArgs e)
{
//Check for input status (we want true)
if (inputStatus)
{
//Check if it already has a decimal (if it does then do nothing)
if (!hasDecimal)
{
//Check to make sure the length is > than 1
//Dont want user to add decimal as first character
if (txtNumberBar.Text.Length != 0)
{
//Make sure 0 isnt the first number
if (txtNumberBar.Text != "0")
{
//It met all our requirements so add the zero
txtNumberBar.Text += btnDecimal.Text;
//Toggle the flag to true (only 1 decimal per calculation)
hasDecimal = true;
}
}
else
{
//Since the length isnt > 1
//make the text 0.
txtNumberBar.Text = "0.";
}

}

}
}

private void btnPlus_Click(object sender, EventArgs e)
{
//Make sure out input box has a value
if (txtNumberBar.Text.Length != 0)
{
//Check the value of our function flag
if (calcFunc == string.Empty)
{
//Flag is empty
//Assign the value in our input
//box to our holder
valHolder1 = System.Double.Parse(txtNumberBar.Text);
//Empty the input box
txtNumberBar.Text = string.Empty;
}
else
{
//Flag isnt empty
//Call our calculate totals method
CalculateTotals();
}
//Assign a value to our calc function flag
calcFunc = "Add";
//Toggle the decimal flag
hasDecimal = false;
}

}
}
}



whenever i put in the parts of the code that include the CalculateTotals method I keep getting an error message saying " The name "CalculateTotals" does not exist in the current context" whats happening?
my code so far is :
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 Calculator
{
public partial class frmCalculator : Form
{
//variables to hold operands
private double valHolder1;
private double valHolder2;
//Varible to hold temporary values
private double tmpValue;
//True if "." is use else false
private bool hasDecimal = false;
private bool inputStatus = true;
//variable to hold Operater
private string calcFunc;

public frmCalculator()
{
InitializeComponent();
}


private void frmCalculator_Load(object sender, EventArgs e)
{

}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}

private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(" This is a Calculator. This calculator can do all the functions of a basic calculator and then some.", "about");
}

private void howToUseThisCalculatorToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("Click the numbers you need and they will appear on the number bar. Zero cannot be selected as the first number. n! is a factorial. √ is a square root sign. ^ is for exponents. GFC stands for Greatest common factor. MS (Memory save) is to add a number to the memory, MR (Memory recall) is used to recall that number, M+ (Memory Addition) is used to add a number to your saved number, and MC (Memory Clear) clears the number saved in the memory.", "How to use the calculator");
}

private void btnOne_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnOne.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnOne.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnTwo_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnTwo.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnTwo.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnThree_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnThree.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnThree.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnFour_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnFour.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnFour.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnFive_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnFive.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnFive.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnSix_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnSix.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnSix.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnSeven_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnSeven.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnSeven.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnEight_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnEight.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnEight.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnNine_Click(object sender, EventArgs e)
{
//Check the inputStatus
if (inputStatus)
{
//Its True
//Append values to the value
//in the input box
txtNumberBar.Text += btnNine.Text;
}
else
{
//Value is False
//Set the value to the value of the button
txtNumberBar.Text = btnNine.Text;
//Toggle inputStatus to True
inputStatus = true;
}
}

private void btnZero_Click(object sender, EventArgs e)
{
//Check the input status
if (inputStatus)
{
//If true
//Now check to make sure our
//input box has a value
if (txtNumberBar.Text.Length >= 1)
{
//Add our zero
txtNumberBar.Text += btnZero.Text;

}

}
}

private void btnDecimal_Click(object sender, EventArgs e)
{
//Check for input status (we want true)
if (inputStatus)
{
//Check if it already has a decimal (if it does then do nothing)
if (!hasDecimal)
{
//Check to make sure the length is > than 1
//Dont want user to add decimal as first character
if (txtNumberBar.Text.Length != 0)
{
//Make sure 0 isnt the first number
if (txtNumberBar.Text != "0")
{
//It met all our requirements so add the zero
txtNumberBar.Text += btnDecimal.Text;
//Toggle the flag to true (only 1 decimal per calculation)
hasDecimal = true;
}
}
else
{
//Since the length isnt > 1
//make the text 0.
txtNumberBar.Text = "0.";
}

}

}
}

private void btnPlus_Click(object sender, EventArgs e)
{
//Make sure out input box has a value
if (txtNumberBar.Text.Length != 0)
{
//Check the value of our function flag
if (calcFunc == string.Empty)
{
//Flag is empty
//Assign the value in our input
//box to our holder
valHolder1 = System.Double.Parse(txtNumberBar.Text);
//Empty the input box
txtNumberBar.Text = string.Empty;
}
else
{
//Flag isnt empty
//Call our calculate totals method
CalculateTotals();
}
//Assign a value to our calc function flag
calcFunc = "Add";
//Toggle the decimal flag
hasDecimal = false;
}

}
}
}

Go to the top of the page
+Quote Post

boeseskeksi
*



post 3 Nov, 2009 - 02:51 AM
Post #19
Hi there,

i Found a little mistake blink.gif

If I try to calculate -3 + -2 the result is -6 crazy.gif

Can somebody help me happy.gif I don´t know how to fix this

here is my code for example

CODE
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 calc2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private double valHolder1;
        private double valHolder2;

        private double tmpValue;

        private bool hasDecimal = false;
        private bool inputStatus = true;

        private string calcFunc;



        private void btn_1_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_1.Text;
            }
            else
            {
                textBox1.Text = btn_1.Text;
                inputStatus = true;
            }


        }

        private void btn_2_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_2.Text;
            }
            else
            {
                textBox1.Text = btn_2.Text;
                inputStatus = true;
            }
        }

        private void btn_3_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_3.Text;
            }
            else
            {
                textBox1.Text = btn_3.Text;
                inputStatus = true;
            }
        }

        private void btn_4_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_4.Text;
            }
            else
            {
                textBox1.Text = btn_4.Text;
                inputStatus = true;
            }
        }

        private void btn_5_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_5.Text;
            }
            else
            {
                textBox1.Text = btn_5.Text;
                inputStatus = true;
            }
        }

        private void btn_6_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_6.Text;
            }
            else
            {
                textBox1.Text = btn_6.Text;
                inputStatus = true;
            }
        }

        private void btn_7_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_7.Text;
            }
            else
            {
                textBox1.Text = btn_7.Text;
                inputStatus = true;
            }

        }

        private void btn_8_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_8.Text;
            }
            else
            {
                textBox1.Text = btn_8.Text;
                inputStatus = true;
            }
        }

        private void btn_9_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                textBox1.Text += btn_9.Text;
            }
            else
            {
                textBox1.Text = btn_9.Text;
                inputStatus = true;
            }
        }

        private void btn_0_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                if (textBox1.Text.Length <= 1)
                {
                    textBox1.Text += btn_0.Text;
                }
            }
        }

        private void btn_plus_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0)
            {
                if (calcFunc == string.Empty)
                {
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    textBox1.Text = String.Empty;
                }
                else
                {

                    CalculateTotals();
                }
                calcFunc = "Add";
                hasDecimal = false;
            }

        }

        private void btn_minus_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0)
            {
                if (calcFunc == String.Empty)
                {
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    textBox1.Text = string.Empty;
                }
                else
                {
                    CalculateTotals();
                }
                calcFunc = "Subtract";
                hasDecimal = false;
            }

        }

        private void btn_ex_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0)
            {
                if (calcFunc == string.Empty)
                {
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    textBox1.Text = String.Empty;
                }
                else
                {
                    CalculateTotals();
                }
                calcFunc = "PowerOf";
                hasDecimal = false;
            }
        }

        private void btn_sqrt_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0)
            {
                tmpValue = System.Double.Parse(textBox1.Text);

                tmpValue = System.Math.Sqrt(tmpValue);
                textBox1.Text = tmpValue.ToString();
                hasDecimal = false;
            }
        }

        private void back_Click(object sender, EventArgs e)
        {
            string str;
            int loc;

            if (textBox1.Text.Length > 0)
            {
                str = textBox1.Text.Substring(textBox1.Text.Length - 1);
                if (str == ".")
                {
                    hasDecimal = false;
                }
                loc = textBox1.Text.Length;
                textBox1.Text = textBox1.Text.Remove(loc - 1, 1);

            }
        }

        private void btn_ce_Click(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;
            hasDecimal = false;


        }

        private void btn_c_Click(object sender, EventArgs e)
        {
            textBox1.Text = string.Empty;

            valHolder1 = 0;
            valHolder2 = 0;
            calcFunc = string.Empty;
            hasDecimal = false;

        }

        private void btn_divi_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0)
            {
                if (calcFunc == string.Empty)
                    valHolder1 = System.Double.Parse(textBox1.Text);
                textBox1.Text = string.Empty;
            }
            else
            {
                CalculateTotals();
            }
            calcFunc = "Divide";
            hasDecimal = false;


        }

        private void btn_multi_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0)
            {
                if (calcFunc == string.Empty)
                {
                    valHolder1 = System.Double.Parse(textBox1.Text);
                    textBox1.Text = string.Empty;
                }
                else
                {
                    CalculateTotals();
                }
                calcFunc = "Multiply";
                hasDecimal = false;
            }
        }

        private void btn_kehr_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0)
            {
                tmpValue = System.Double.Parse(textBox1.Text);
                tmpValue = 1 / tmpValue;
                textBox1.Text = tmpValue.ToString();
                hasDecimal = false;
            }
        }

        private void btn_plusminus_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                if (textBox1.Text.Length > 0)
                {
                    valHolder1 = -1 * System.Double.Parse(textBox1.Text);
                    textBox1.Text = valHolder1.ToString();
                }

            }





        }

        private void btn_equals_Click(object sender, EventArgs e)
        {
            if (textBox1.Text.Length != 0 && valHolder1 != 0)
            {
                CalculateTotals();
                calcFunc = String.Empty;
                hasDecimal = false;

            }



        }

        private void btn_komma_Click(object sender, EventArgs e)
        {
            if (inputStatus)
            {
                if (!hasDecimal)
                {
                    if (textBox1.Text.Length != 0)
                    {
                        if (textBox1.Text != "0")
                        {
                            textBox1.Text +=  btn_komma.Text;
                            hasDecimal = true;
                        }
                  
                    }
                    else
                    {
                        textBox1.Text = "0,";
                    }
                }
            }
      
       }
        private void CalculateTotals()
        {
            valHolder2 = System.Double.Parse(textBox1.Text);
            switch (calcFunc)
            {
                case "Add":
                    valHolder1 = valHolder1 + valHolder2;

                    break;

                case "Subtract":

                    valHolder1 = valHolder1 - valHolder2;

                    break;
                case "Divide":
                    valHolder1 = valHolder1 / valHolder2;

                    break;

                case "Multiply":

                    valHolder1 = valHolder1 * valHolder2;

                    break;

                case "PowerOf":

                    valHolder1 = System.Math.Pow(valHolder1, valHolder2);
                    break;
            }
            textBox1.Text = valHolder1.ToString();
            inputStatus = false;
        }
    }
}
    
Go to the top of the page
+Quote Post


Fast ReplyReply to this topicStart new topic
4 User(s) are reading this topic (4 Guests and 0 Anonymous Users)
0 Members:

 


Lo-Fi Version Time is now: 11/21/09 12:02PM

Live C# Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

C# Tutorials

Reference Sheets

C# Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month