How can I use if condition to add values

Viewed 408

I want to obtain a total of three values:

when none of the values is null, the total calculates successfully but when one or more of the values is null,

it returns an error:

"input string was not in correct format"

Below is the code:

double TotalVar = double.Parse(ExScore.Tables[0].Rows[i]["CAT1"].ToString()) + 
double.Parse(ExScore.Tables[0].Rows[i]["CAT2"].ToString()) + 
double.Parse(ExScore.Tables[0].Rows[i]["CAT3"].ToString()) + 
double.Parse(ExScore.Tables[0].Rows[i]["EXAM"].ToString());
3 Answers

Use local function like this to safely parse data :

double Parse(string data)
{
    return double.TryParse(data, NumberStyles.AllowDecimalPoint, 
        CultureInfo.InvariantCulture, out double val) ? val : 0;
}
if(ExScore == null || ExScore.Tables[0] == null ||
  IsNullOrEmpty(ExScore.Tables[0].Rows[i]["CAT1"]) || 
  IsNullOrEmpty(ExScore.Tables[0].Rows[i]["CAT2"]) || 
  IsNullOrEmpty(ExScore.Tables[0].Rows[i]["CAT3"]) || 
  IsNullOrEmpty(ExScore.Tables[0].Rows[i]["EXAM"])
)
{
    //throw exception
    //set value by default
}

//calcul normally

public bool IsNullOrEmpty(object value)
{
    return value == null || string.IsNullOrEmpty(value.ToString());
}

Create a console app and test the app below. Everything you need is in the code below. Note: It is bad to direct cast strings without a minimal error handling, also you can/will have problems with "." or "," decimal separators in these casts. - Different regions use different decimal separators, and this can impact the quality of your results.

   class Program
{
    static void Main(string[] args)
    {
        //SumValues(
        //ExScore.Tables[0].Rows[i]["CAT2"].ToString(),
        //ExScore.Tables[0].Rows[i]["CAT3"].ToString(),
        //ExScore.Tables[0].Rows[i]["EXAM"].ToString()
        //);

       Console.WriteLine(SumValues("100,32", "100,08", "100,10",null));
       Console.WriteLine(SumValues("abcsdf", "ba123", "100,10", null));
       Console.WriteLine(SumValues("100,32", "100,08", "100,10", null));
       Console.ReadLine();
    }


    //simple function that will try to sum any number of strings you pass
    public static double SumValues(params string[] values)
    {
        double sum=0;

        foreach (var item in values)
        {
            //if the string is null, empty or white space, proceed to the next iteration in the loop
            if (string.IsNullOrWhiteSpace(item))
                continue;

            if (IsNumeric(item))
                sum += double.Parse(item);
        }

        return sum;
    }

    //Minimal 'error handling' function to avoid exceptions parsing strings
    public static bool IsNumeric(string s)
    {
        double output;
        return double.TryParse(s, out output);
    }
}
Related