1

So I tried to create a method, where I get a value from the TextBox and check if that value is a number in the SET method.

I get an error when converting the TextBox value and I want to display it as a try/catch exception, but that has to be verified in the SET method ( Summary.FirstNumber, where SET method checks if it's a number, else it returns an error in ErrorMsg)

NOTE: I have 2 namespaces with classes

1st: Projekt_STROKA.Calculator

2nd: MathFunctions.Summary

This is the how I attempted to make it work:

The call when the button is pressed in Projekt_STROKA.Calculator

protected void btnSum_Click(object sender, EventArgs e)
{
    MathFunctions.Summary summary = new MathFunctions.Summary();
    summary.FirstNumber = Convert.ToDouble(txbFirstNumber.Text); 
    //throws error if the input value is not a number
    summary.SecondNumber = Convert.ToDouble(txbSecondNumber.Text);
    txbSummary.Text = summary.Sum(summary.FirstNumber, summary.SecondNumber).ToString();
}

The functions in MathFunctions.Summary

Projekt_STROKA.Calculator calc = new Projekt_STROKA.Calculator();
private double firstNumber;
private double secondNumber;

public double FirstNumber
{
    set
    {
        if (IsNumber(firstNumber) == true)
            firstNumber = value;
        else
            throw new ArgumentNullException();
        /*        
        try
        {
            if (IsNumber(firstNumber) == true)
                firstNumber = value;        
        }
        catch (Exception ex)
        {
            calc.setError(ErrorMsg(ex.Message));          
        }
        */
    }
    get { return firstNumber; }
}

public string ErrorMsg(string message)
{
    return message;
}

public bool IsNumber(double number)
{
    if (number.GetType() == typeof(double))
        return true;
    else
        return false;
}

public double Sum(double firstNum, double secondNum)
{
    return Math.Round((firstNum + secondNum), 2);
}
McBooley
  • 433
  • 1
  • 5
  • 16

1 Answers1

0

I suggest you use the following snippet:

try
        {
            Object o = Console.ReadLine();
            double d = double.Parse(o.ToString());
        }
        catch (ArgumentException ex)
        {
            //
        }
        catch (FormatException ex)
        {
            //
        }
        catch (OverflowException ex)
        {
            //
        }


Use the same way for other types: int.Parse(), float.Parse(), decimal.Parse ...

Green Falcon
  • 818
  • 3
  • 17
  • 48