Click here to Skip to main content
15,908,437 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
ASM
Good day all, I need some help

I have 10 text boxes to add to get the total sum .. some thing like this

C#
int totalQLoaded = int.Parse(Txt50ClCokeQuantityLoaded.Text) + int.Parse(Txt50ClFantaQuantityLoaded.Text) + int.Parse(Txt50ClSpriteQuantityLoaded.Text)
                + int.Parse(TxtBCokeQuantityLoaded.Text) + int.Parse(TxtBEvaQuantityLoaded.Text) +

//the calculation works fine if all the text boxes are filled with numbers.


SQL
but in a situation where some fields are left blank how do i get the total sum ignoring  those field that are blank..

thanks for your time I appreciate
Posted

1 solution

Simple: create a method that accepts a string and returns the value or a default if the string is blank:
C#
private int GetValue(string s)
    {
    int value = 0;
    if (!string.IsNullOrWhiteSpace(s))
        {
        int.TryParse(s, out value);
        }
    return value;
    }
Then all you have to do is call that instead:
C#
int totalQLoaded = GetValue(Txt50ClCokeQuantityLoaded.Text) + 
                   GetValue(Txt50ClFantaQuantityLoaded.Text) +
...
 
Share this answer
 
Comments
Difameg Network Nigeria 4-Nov-13 9:41am    
thanks bro, it worked fine
Difameg Network Nigeria 4-Nov-13 9:43am    
can you please explain it to me (!string.IsNullOrWhiteSpace(s))
{
int.TryParse(s, out value);
I want to have an idea of that....thanks, i really do appreciate
OriginalGriff 4-Nov-13 9:53am    
The first checks if the string has any significant content: i.e. it isn't null and it isn't white space (tabs, spaces, that kind of thing) - it needs to have at least one actual character to pass.
The second does much what int.parse does, but without throwing an exception if the string is not a valid number - it returns a "true / false" value instead, which I am ignoring in this case.

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