How to Create a Calculator App in C#.NET in a easy way[with source code]
code:
import library:
using System.Data;
inside the form class:
private string currentCalculation = "";
create following function:
1. for button text extraction
private void button_click(object sender, EventArgs e) { currentCalculation += (sender as Button).Text; txtOutput.Text = currentCalculation; }
2. for calculation
private void button_Equals_click(object sender, EventArgs e) { string formattedCalculation = currentCalculation.ToString(); try { txtOutput.Text = new DataTable().Compute(formattedCalculation, null).ToString(); currentCalculation = txtOutput.Text; } catch(Exception ex) { txtOutput.Text = "ERROR"; currentCalculation = ""; } }
3. for clearing button
private void button_Clear_click(object sender, EventArgs e) { txtOutput.Text = "0"; currentCalculation = ""; }
4. for clearing entry button
private void button_clearEntery_click(object sender, EventArgs e) { if (currentCalculation.Length > 0) { //1+1 currentCalculation = currentCalculation.Remove(currentCalculation.Length - 1, 1); } txtOutput.Text = currentCalculation; }
call these function in respective button clicking event!