public bool IsOperator(TextBox textbox, string name)
{
if (name != "+" || name != "-" || name != "*" || name != "/")
{
MessageBox.Show(name + " Must be +, -, *, or /.", "Entry Error");
txtOperator1.Focus();
return false;
}
return true;
}
I am making a basic calculator and I have to validate that the operand entered into the text box is either a +, -, *, or /. I coded this as a generic validating method have correctly called it in my program. However, when I run the program and enter any of the operands that should be valid it pops up and tells me they're not. I'm really stuck and would greatly appreciate any help.
Edit: Here is the other parts of my code that goes with this validation. The other validators are working fine it's just the IsOperator that is giving me grief.
private void btnCalculate_Click(object sender, EventArgs e)
{
try
{
if (IsValidData())
{
decimal operand1 = Convert.ToDecimal(txtOperand1);
string operator1 = Convert.ToString(txtOperator1);
decimal operand2 = Convert.ToDecimal(txtOperand2);
decimal result = Calculate(operand1, operator1, operand2);
txtResult.Text = result.ToString("n4");
txtOperand1.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\n\n" + ex.GetType().ToString() + "\n" + ex.StackTrace, "Exception");
}
}
public bool IsValidData()
{
IsPresent(txtOperand1, "Operand 1") &&
IsDecimal(txtOperand1, "Operand 1") &&
IsWithinRange(txtOperand1, "Operand 1", 1, 999999) &&
IsPresent(txtOperator1, "Operator") &&
IsOperator(txtOperator1, "Operator") &&
IsPresent(txtOperand2, "Operand 2") &&
IsDecimal(txtOperand2, "Operand 2") &&
IsWithinRange(txtOperand2, "Operand 2", 1, 999999);
}
private decimal Calculate(decimal operand1, string operator1, decimal operand2)
{
//This method performs the calculation based on what operand was entered
if (txtOperator1.Text == "+")
{
decimal calculationResult = operand1 + operand2;
return calculationResult;
}
else if (txtOperator1.Text == "-")
{
decimal calculationResult = operand1 - operand2;
return calculationResult;
}
else if (txtOperator1.Text == "*")
{
decimal calculationResult = operand1 * operand2;
return calculationResult;
}
else
{
decimal calculationResult = operand1 / operand2;
return calculationResult;
}
}