0

I have a question about creating calculator in C# Windows Form Application. I want it to be possible write with form buttons an expression in textbox so for example 2+3+7= and after pressing "=" button program will read all digits and signs and perform calculation... I don't know from where to start and how could do it in such a way. Any help to any reference or smth to look at how to start doing such a expressions?

Main thing is how to read, seperate and after calculate values from textbox.

Thanks.

Sangsom
  • 257
  • 6
  • 15
  • check this post http://stackoverflow.com/questions/8656282/c-sharp-calculator-typing-by-pressing-buttons – Tun Zarni Kyaw Jan 04 '14 at 11:24
  • 1
    http://en.wikipedia.org/wiki/Parsing You need to parse your expression into tokens, then apply order of math to it. (2 + 3 + 7) * 4 => (5 + 7) * 4 => 12 * 4 – CSharpie Jan 04 '14 at 11:28
  • I wrote a small library a while back to parse and evaluate arithmetic expressions. https://github.com/patriksvensson/arithmetica – Patrik Svensson Jan 04 '14 at 12:12

1 Answers1

1

With the Split method you could solve this rather easy. Try this:

private void button1_Click(object sender, EventArgs e)
{
  string[] parts = textBox1.Text.Split('+');
  int intSum = 0;
  foreach (string item in parts)
  {
    intSum = intSum + Convert.ToInt32(item);
  }
  textBox2.Text = intSum.ToString();
}

If you would like to have a more generic calculation, you should look at this post: In C# is there an eval function?

Where this code snippet would do the thing:

public static double Evaluate(string expression)
{
  System.Data.DataTable table = new System.Data.DataTable();
  table.Columns.Add("expression", string.Empty.GetType(), expression);
  System.Data.DataRow row = table.NewRow();
  table.Rows.Add(row);
  return double.Parse((string)row["expression"]);
}

private void button1_Click(object sender, EventArgs e)
{
  textBox2.Text = Evaluate(textBox1.Text).ToString();
}
Community
  • 1
  • 1
carleson
  • 728
  • 1
  • 5
  • 14
  • Thanks for answer, actually I had this Evaluate method found too. It works good, but I thought I need to write that calculation in different way for studies.. Thanks anyway :) – Sangsom Jan 06 '14 at 08:29