简体   繁体   中英

how to add multiple textbox numbers, and store the sum as a double in variable

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);

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!

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);

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;

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 double s. So you can do something as simple as this:

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

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; })

Little fun with Linq .

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

Where as AsDouble from neoistheone's answer .

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM