Click here to Skip to main content
15,904,023 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi
I have a listbox and textbox
I need to add the sum of all values in a listbox and post the total in a textbox including textbox value.

Technology - C#.net using windows form
Posted
Comments
OriginalGriff 4-May-11 5:06am    
And what have you tried so far?

Here is how to do it:

C#
static int Sum(ListBox listBox) {
    int result = 0;
    for (int index = 0; index < listBox.Items.Count; ++index) {
        int value;
        if (!int.TryParse(listBox.Items[index], out value)) continue;
        result += value;
    }
    return result;
}

//...

int sum = 0;

//what does it mean "including text box value"?
//perhapse, this (optional):
int textBoxValue = 0;
int.TryParse(MyTextBox.Text, out textBoxValue);
sum += textBoxValue;

sum += Sum(MyListBox);

MyTextBox.Text = sum.ToString());


If the numeric type if not int, changes the code accordingly (use double or whatever in Sum).

—SA
 
Share this answer
 
v7
Comments
Sandeep Mewara 6-May-11 0:01am    
A full good concise code.... what more OP can ask for! 5!
Sergey Alexandrovich Kryukov 6-May-11 0:05am    
Thank you, Sandeep.
--SA
Tarun.K.S 6-May-11 2:06am    
5+
Sergey Alexandrovich Kryukov 6-May-11 2:37am    
Thank you, Tarun.
--SA
Do it like this :

C#
double total=0;
foreach (object item in listBox1.Items)
{
    total += (double)item;
}
txtTotal.Text = total.ToString();


or if you have the values as string, then use double.Parse(item) instead of (double)item.
 
Share this answer
 
v2
Comments
Kim Togo 4-May-11 5:24am    
Good answer, 5
Tarun.K.S 4-May-11 5:50am    
Thanks! :)
Tarun.K.S 4-May-11 6:00am    
great!
Sergey Alexandrovich Kryukov 5-May-11 16:53pm    
Tarun, you need to be sure that each element is double. My 4, therefore.
Please see my answer for safer code.
Tarun.K.S 6-May-11 2:04am    
Actually I did mention below my code that, if its a string, you can use Double.Parse. Anyway thanks for the 4.
Another way is u can use Generics and do this in a single line

Like

int total = ListBox1.Items.Cast<listitem>().Select<listitem,>(s => Convert.ToInt32(s.Text)).Aggregate((a, b) => a + b);
</listitem>


but as per KIM TOGO, the short and sweet

ListBox1.Items.Cast<listitem>().Sum(item => int.Parse(item.Text));</listitem>
 
Share this answer
 
v4
Comments
nit_singh 4-May-11 5:31am    
try this..it will work
Kim Togo 4-May-11 5:49am    
Nice, love Linq.
What about .Sum(item => int.Parse(item.Text)), more simple ?
My 5 for Linq.
nit_singh 4-May-11 6:13am    
Yes yours solution is simple and sweet...Thanks

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