1

If I click on 5+5 on my calculator it will display 5+5 in my first text box (I have two of them: one for the sum and one for the result). I get this error after pressing =

enter image description here

I think it it because when I hover over Sum.Text it is displaying 5+5 and I need to split it up but I do not know how.

Here is my code.

private void Addition_Click(object sender, EventArgs e)
{
    dbl_FirstNumber = Convert.ToDouble(Sum.Text);
    Sum.AppendText ("+");
    Operation = 1;
}

private void equals_Click(object sender, EventArgs e)
{
    switch (Operation)
    {
        case 1:
            Result.Text = Convert.ToString(Convert.ToDouble(Sum.Text) + dbl_FirstNumber);    
            break;   
        case 2:
            Result.Text = Convert.ToString(Convert.ToDouble(Sum.Text) - dbl_FirstNumber);
            break;                                                                          
        case 3:                                                                            
            Result.Text = Convert.ToString(Convert.ToDouble(Sum.Text) * dbl_FirstNumber);
            break;
        case 4:
            Result.Text = Convert.ToString(Convert.ToDouble(Sum.Text) / dbl_FirstNumber);
            break;                    
        }
    }
}                                                                                    
Mike G
  • 4,232
  • 9
  • 40
  • 66
unreal1357
  • 11
  • 3
  • 1
    Well, your problem is quite bigger then you think it is. The C#-compiler cannot know that when you input text such as `5 + 5` you need the result of this operation. You have to parse the string in any way extracting all operators and the numbers. You may however have a look at this tutorial: http://www.dreamincode.net/forums/topic/32968-basic-calculator-in-c%23/ – MakePeaceGreatAgain Nov 17 '15 at 13:25
  • How would I parse the string // just seen the link, thanks I'll check it out – unreal1357 Nov 17 '15 at 13:29
  • Look into a project called Ncalc (http://ncalc.codeplex.com). It has the ability to evaluate a string for its mathematical operators. @HimBromBeere: that "basic" calculator tutorial is extremely inelegant to say the least. I really can't suggest following that tutorial. – S. Brentson Nov 17 '15 at 13:51
  • When I get home I'll have a look at it, thanks – unreal1357 Nov 17 '15 at 13:54
  • Another more elegant solution without adding external libraries involves using the DataTable() Compute() method. (http://stackoverflow.com/a/2859130). – S. Brentson Nov 17 '15 at 13:55

1 Answers1

2

Using the method suggested here

private void equals_Click(object sender, EventArgs e)
{
    Result.Text = new System.Data.DataTable().Compute(Sum.Text, null);    
}   
Community
  • 1
  • 1
S. Brentson
  • 454
  • 4
  • 7