1

Here is my issue. I want to be able to sum the values of 10 textbox's into a double type variable.

The problem is that the textbox values are populated by a database and are not always filled. I want to be able to sum the values of all 10 without forcing a default value of zero in textbox's that are null.

amount = Convert.ToDouble(amount1TextBox.Text + amount2TextBox.Text + amount3TextBox.Text + amount4TextBox.Text + amount5TextBox.Text + amount6TextBox.Text + amount7TextBox.Text + amount8TextBox.Text + amount9TextBox.Text + amount10TextBox.Text);
4
  • What's the problem with forcing a default value of zero? Wouldn't you get the same thing? Commented Oct 22, 2013 at 13:38
  • " without forcing a default value of zero in textbox's that are null." huh? Commented Oct 22, 2013 at 13:38
  • because I am saving the values into another database and it would make the program think that the value ZERO is actually a value that needs to be saved. This is a database normalization project. Commented Oct 22, 2013 at 13:39
  • @TimSchmelter, if there is a null value, the program throws an error. If I added a default value of zero in textboxs that are null the error would not be thrown. That solution would not work for me Commented Oct 22, 2013 at 13:40

7 Answers 7

5

How about an extension method for the TextBox:

namespace System
{
    public static class Extensions
    {
        public static double AsDouble(this TextBox t)
        {
            double val;
            double.TryParse(t.Text, out val);
            return val;
        }
    }
}

and then you could use that like this:

var amt = amount1TextBox.AsDouble() +
    amount2TextBox.AsDouble() +
    amount3TextBox.AsDouble() +
    amount4TextBox.AsDouble() +
    amount5TextBox.AsDouble() +
    amount6TextBox.AsDouble() +
    amount7TextBox.AsDouble() +
    amount8TextBox.AsDouble() +
    amount9TextBox.AsDouble() +
    amount10TextBox.AsDouble();

This also means that any other time you need to get the value of the TextBox as a double it's really straight forward; on any form in the application!

Sign up to request clarification or add additional context in comments.

3 Comments

+1 I like the extension, but not its name. perhaps GetValueAsDouble will be better
@SriramSakthivel Yup, I agree with you there.
+1 for the answer but i think this is "over kill" a simple private function that receives params TextBoxs[] would be better but that just me.
4

Sorry, you'll need to check the value of each text box. It will be a little cleaner to make that a separate function:

public double GetValue(string text)
{
    if(string.IsNullOrEmpty(text)) 
        return 0;

    double value;

    if(double.TryParse(text, out value))
        return value;

    // not parsable
    return 0;
}

and call

amount = 
    GetValue(amount1TextBox.Text) + 
    GetValue(amount2TextBox.Text) + 
    GetValue(amount3TextBox.Text) + 
    GetValue(amount4TextBox.Text) + 
    GetValue(amount5TextBox.Text) +         
    GetValue(amount6TextBox.Text) + 
    GetValue(amount7TextBox.Text) + 
    GetValue(amount8TextBox.Text) + 
    GetValue(amount9TextBox.Text) + 
    GetValue(amount10TextBox.Text);

1 Comment

I think you don't need Convert.ToDouble call :)
3

You cannot add strings and expect that they are summed numerically. You will just concatenate the text.

You should use Double.TryParse to check if the string can be parsed:

double d1;
double.TryParse(amount1TextBox.Text, out d1));
double d2
double.TryParse(amount2TextBox.Text, out d2));
// and so on ...

double result = d1 + d2 + .... + d10;

Comments

2

You have a couple of things going on here. First is that you're using the + operator on strings, which is going to concatenate them as strings instead of sum them as numbers. So you need to convert them to numbers first.

Of course, that might get a little bloated with all of these text boxes. But it sounds like you have some business logic which may make it easier. You don't need to force the text boxes to display a 0, but you can default their value to 0 in the absence of a valid value.

You can start by creating a simple extension method for TextBox to get its numeric value, or a default of 0. Something like this:

public static double GetAmount(this TextBox t)
{
    double result = 0;
    double.TryParse(t.Text, out result);
    return result;
}

For any given TextBox you can now easily get the numeric value with:

amount1TextBox.GetAmount();

This also means that you can sum them instead of concatenating them, and you don't need to convert the sum to a double because the amounts are already doubles. So you can do something as simple as this:

amount = amount1TextBox.GetAmount() +
         amount2TextBox.GetAmount() +
         //...
         amount10TextBox.GetAmount();

2 Comments

I don't think I fully understand extension methods. Can you elaborate? for instance, where do I put the GetAmount extention
@CodeSlinger: It would need to be in a public static class in an included namespace. (At the root of that namespace, it can't be internal to another class for example.) There's a good description of them here: msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx Basically an extension method is a kind of syntactic sugar for a normal static method, putting that method on an object ("extending" the object without actually modifying it). It can even be called as a normal method and passed the object it "extends" if you want.
2

A bit of LINQ:

amount = Controls.OfType<TextBox>()
                 .Where(tb => tb.Name.StartsWith("amount"))
                 .Select(tb => tb.Text)
                 .Where(s => !String.IsNullOrEmpty(s))
                 .Sum(s => Int32.Parse(s));

Assumed your textboxes are empty or have numbers. If it is possible to input some text in thses textboxes, then last line should look like:

.Sum(s => { int i; return Int32.TryParse(s, out i) ? i : 0; })

3 Comments

how would this iterate through all textboxes?
@CodeSlinger is it winforms, wpf or web forms application?
@CodeSlinger then use Controls property of control where your textboxes are placed (by default it will be Controls property of your form). OfType<TextBox> filters only textboxes (buttons, lables, etc are filtered out). And then I check textbox name to start with amount string (as all you textboxes do).
2

Little fun with Linq.

var total = new[]{ amount1TextBox, amount2TextBox ,amount3TextBox, ...}
            .Sum(x=> x.AsDouble());

Where as AsDouble from neoistheone's answer.

Comments

1

i know you already choose an answer that suite you but because you asked for an example, and because other people might want different solutions ill put my way here.

private  double GetSum(params TextBox[] arr)
    {
        double sum = 0;
        double temp;
        foreach (TextBox txt in arr)
        {
            double.TryParse(txt.Text,out temp);
            sum += temp;
        }
        return sum;
    }

and use it:

double a = GetSum(new TextBox() { Text = "1" }, new TextBox() { Text = "1" }, new TextBox() { Text = "1" }, new TextBox() { Text = "a" });

on a pesonal note, i like linq its great for data manipulation , but not every problem, requires a complex solution, i rather stay with a simple clean solution that is easy to maintain and easy to understand by others. but again that just me :)

2 Comments

I agree. That's why I chose Tim Schmelters answer. Very easy to follow. I like this answer too because it simplified the extension method answers. I'm sure I can use this in other areas. Thanks for getting back to me
any time, i help you, others help me, you help others :) win win

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.