calculate the expression of a text Box

Suku76
Posted by Suku76 under C# category on | Points: 40 | Views : 552
private void button1_Click(object sender, EventArgs e)
{
try
{
int intSum = 0;
string[] parts;
switch (val)
{
case "+":
parts = textBox1.Text.Split('+');
foreach (string item in parts)
{
intSum = intSum + Convert.ToInt32(item);
}
textBox2.Text = intSum.ToString();
break;
case "-":
parts = textBox1.Text.Split('-');
foreach (string item in parts)
{
intSum = (-intSum) - Convert.ToInt32(item);
}
textBox2.Text = intSum.ToString();
break;
case "%":
parts = textBox1.Text.Split('%');
intSum = 1;
foreach (string item in parts)
{
intSum = intSum % Convert.ToInt32(item);
}
textBox2.Text = intSum.ToString();
break;
case "*":
parts = textBox1.Text.Split('*');
intSum = 1;
foreach (string item in parts)
{
intSum = intSum * Convert.ToInt32(item);
}
textBox2.Text = intSum.ToString();
break;
case "/":
parts = textBox1.Text.Split('/');
intSum = 1;
foreach (string item in parts)
{
intSum = intSum / Convert.ToInt32(item);

}
textBox2.Text = intSum.ToString();
break;
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
string val;
private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e)
{
// var regex = new System.Text.RegularExpressions.Regex(@"[^a-zA-Z0-9\s]");
var regex = new System.Text.RegularExpressions.Regex(@"[^0-9%*+-/\s]");
var regex1 = new System.Text.RegularExpressions.Regex(@"[^%*+-/\s]");
if (regex.IsMatch(e.KeyChar.ToString()))
{
e.Handled = true;
MessageBox.Show("Characters are Not allowed!");
}
if (!regex1.IsMatch(e.KeyChar.ToString()))
{ val = e.KeyChar.ToString(); }

}

Comments or Responses

Login to post response