Click here to Skip to main content
15,883,758 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
This my code so far to calculate numbers using two textboxes upon choosing ADD radio button and clicking on Calculate button.

C#
 private void btnCalculate_Click(object sender, EventArgs e)
        {
            //try

            //{

            //Local  variables
            double dFirstNumber; // To hold FirstNumber
            double dSecondNumber; // To hold SecondNumber
            double dResult; // To Hold Result


            // Validate First Number  using double.TryParse 

            if (double.TryParse(txtFirstNumber.Text, out dFirstNumber))


            //Validate second number using double.TryParse 
            {
                if (double.TryParse(txtSecondNumber.Text, out dSecondNumber))


                    // Validate Result  using double.TryParse 
                {
                    if (double.TryParse(txtResult.Text, out dResult))
                    {


                        // do addition when  Add radio button is chosen
                        //and calculate button is clicked

                        if (radAdd.Checked)

                            //Add First and second Number
                         
                           dResult = dFirstNumber + dSecondNumber;
                    }

                    {

                        txtResult.Text = dResult.ToString("n1");
                    }
                }
            }
        }
    }
}



How can I add code for subtract(radSubtract), multiply(radmultiply) and divide(raddivide) radio buttons using else if?

Also, trying to use try-catch block to check. If First and second textboxes have NO number entered and Calculate button is clicked then throw exception that says 'First Number is not valid'.

If First box has number entered BUT Second one has no number entered then throw exception that says 'Second Number is not valid'.

And also throw exception when text boxes have numbers BUT no radio button is checked after Calculate button is clicked. Exception should say "please choose one of the radio buttons."

Thank you for your time
Posted
Comments
Sergey Alexandrovich Kryukov 29-Jan-16 19:39pm    
This is not a question about anything certain. All you need is to embrace the idea of separation or concerns or divide et impera (divide and rule).
Your problem is just that you throw everything in one pile. Radio button is one thing, "if" is another one, "try-catch" is something else. You need to be able to freely combine what you need. Try-catch is not used "to check", it should not be used locally. You did not explain the purpose of radio button. And so on...

It's hard to help you because this is a question about nothing. No problem is really formulated. You cannot ask "how can you add code" (unless you want to hear "by writing it"), because you did not explain what you want to achieve by adding it.

—SA
Philippe Mori 29-Jan-16 21:24pm    
Don't annotate variable with their type in variable name. It make refactoring difficult and it is useless these days with editors that can should definition with a tootip...

Avoid declaring variable before their first use.
koolprasad2003 29-Jan-16 23:08pm    
Its a validation part or an assignment that you want to complete. I think given solutions are enough to resolve your issue. Please accept them as answer as it has resolve your issue

I think your structure of the nested if statements is your first problem.
Validate the first number
Validate the second number
(There's no reason to validate the result since you're about to overwrite it!)
Then calculate the result based on the radio buttons. (There could be errors here! e.g. divide by zero or overflow)
Report result.

An exception is probably not what you want for the error handling, since from a button click handler, there's no good place outside the method to catch the exception. Instead, add a multiline Label or readonly TextBox control to display any error messages.

Not complete code, but something like:
C#
private const string BadFirstNumber = "Bad first number"; // better wording is up to you!
private const string BadSecondNumber = "Bad second number";
private const string DivisionByZero = "Division by zero";
private const string NoOperationSelected = "No operation selected";
private const string NewLine = "\n";

private void btnCalculate_Click(object sender, EventArgs e)
{
  //Local  variables
  double dFirstNumber; // To hold FirstNumber
  double dSecondNumber; // To hold SecondNumber
  double dResult; // To Hold Result
  List<string> messages = new List<string>();
  bool success = true;  // assume all will go well
 
  // Validate First Number  using double.TryParse 
  if (!double.TryParse(txtFirstNumber.Text, out dFirstNumber))
  {
    messages.Add(BadFirstNumber);
    success = false;
  }

  // It's probably a good idea to validate both input values
  //Validate second number using double.TryParse 
  if (!double.TryParse(txtSecondNumber.Text, out dSecondNumber))
  {
    messages.Add(BadSecondNumber);
  } 


  if (success)
  {
    try
    {
      if (radAdd.Checked)
        dResult = dFirstNumber + dSecondNumber;
      else if (radSubtract.Checked)
        dResult = dFirstNumber - dSecondNumber;
      else if (...)
        // etc.
      else
      {
        messages.Add(NoOperationSelected);
        success = false;
      }
    }
    catch (DivideByZeroException)
    {
      messages.Add(DivisionByZero);
    }
    catch (OverflowException)
    {
      messages.Add(ArithmeticOverflow);
    }
 
    if (success)
    {
      txtResult.Text = dResult.ToString("n1");
      messages.Add(SuccessfulResult);
    }
    lblMessages.Text = string.Join(NewLine, messages);
  }
}

There are other designs that would be better but this is a good start and not too different from where you are starting.
 
Share this answer
 
Comments
Sascha Lefèvre 29-Jan-16 20:06pm    
+5Instead of NewLine = "\n" I would suggest Environment.NewLine.
Matt T Heffron 29-Jan-16 20:07pm    
Thanks!
Yes I knew that was out there but couldn't remember the exact name. (If I had guessed I'd have been right!)
Member 11829482 29-Jan-16 20:08pm    
I am getting error on this line messages.Add(ArithmeticOverflow);
"AritmaticOverFlow doesn't exist in the current context"

and on this line :
txtResult.Text = dResult.ToString("n1");
messages.Add(SuccessfulResult);
"SuccessfulResult doesn't exist in the current context"

and on this line:
}
lblMessages.Text = string.Join(NewLine, messages);
}
"lblMessages doesn't exist in the current context"


and on:
} (this one also highlighted Red)
Matt T Heffron 29-Jan-16 20:10pm    
Recall how I said: "Not complete code, but something like"
I didn't try to compile this.
You should be able to figure out what is missing or incorrect.
I'm NOT going to do ALL of your homework!
Member 11829482 29-Jan-16 20:09pm    
Here is the code again with other radio buttons added for calculation
private void frmMain_Load(object sender, EventArgs e)
{

}

private const string BadFirstNumber = "Bad first number"; // better wording is up to you!
private const string BadSecondNumber = "Bad second number";
private const string DivisionByZero = "Division by zero";
private const string NoOperationSelected = "No operation selected";
private const string NewLine = "\n";


private void btnCalculate_Click(object sender, EventArgs e)

{

//Local variables
double dFirstNumber; // To hold FirstNumber
double dSecondNumber; // To hold SecondNumber
double dResult; // To Hold Result
List<string> messages = new List<string>();
bool success = true; // assume all will go well

// Validate First Number using double.TryParse
if (!double.TryParse(txtFirstNumber.Text, out dFirstNumber))
{
messages.Add(BadFirstNumber);
success = false;
}

// It's probably a good idea to validate both input values
//Validate second number using double.TryParse
if (!double.TryParse(txtSecondNumber.Text, out dSecondNumber))
{
messages.Add(BadSecondNumber);
}

if (success)
{
try
{
if (radAdd.Checked)
dResult = dFirstNumber + dSecondNumber;
else if (radSubtract.Checked)
dResult = dFirstNumber - dSecondNumber;
else if (radMultiply.Checked)
dResult = dFirstNumber * dSecondNumber;

else if (radDivide.Checked)
dResult = dFirstNumber / dSecondNumber;


else
{
messages.Add("You must choose OnEnabledChanged of the Operation options");
success = false;
}
}
catch (DivideByZeroException)
{
messages.Add(DivisionByZero);
}
catch (OverflowException)
{
messages.Add(ArithmeticOverflow);
}

if (success)
{
txtResult.Text = dResult.ToString("n1");
messages.Add(SuccessfulResult);
}
lblMessages.Text = string.Join(NewLine, messages);
}
}
First, the whole point of using RadioButtons is that one, and only one, of them is going to be "checked" at all times.

Let's assume you have four RadioButtons, 'rbAdd, 'rbSubtract ... etc. Select them and assign the same 'CheckChanged EventHandler to all of them; then:
C#
// this is not executable code; it is a sketch for executable code

private RadioButton selectedRadioButton;

private void AllRadioButtons_CheckedChanged(object sender, EventArgs e)
{
    var thisRB = sender as RadioButton;

    if (thisRB.Checked) selectedRadioButton = thisRB;
}
Now, in your 'calculate method:
C#
// this is not executable code; it is a sketch for executable code

private void btnCalculate_Click(object sender, EventArgs e)
{
    // validate the content of the two TextBoxes
    // if not valid: clear TextBoxes and exit ?
    // throw error ?

    // int n1 = validate TextBox1
    // int n2 = validate TextBox2

    int result;

    switch (selectedRadioButton.Name)
    {
        case "rbAdd":
            result = n1 + n2;
            break;

        case "rbSubtract":
            break;

        default:
            break;
    }

    // write the 'result into a TextBox
}
 
Share this answer
 
if(radio_add.SelectedItem.Text=="Add")
{
// function for addition
}
else if(radio_sub.SelectedItem.Text=="Sub")
{
// function for substraction
}
else
{
//Alert Message(please select an method
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900