0

Im trying to add numbers together inside a list box. First of all i put the numbers inside the listbox into an array and integers.

I now want to sum all the numbers together inside the list_box to give me a total.

The way i was going to approach this was in a loop and add each number incrementally.

Any help would be very much appreciated, as im really struggling after just starting my HND so im at a extremly very basic level with only covering some basic methods.

    private void rb_sum_CheckedChanged(object sender, EventArgs e)
    {

        //array is needed here at this point
        string boxnumbers = list_box.Text;
        int[] boxnumbers1 = new int[10];

        int answer;

        do
        {
            boxnumbers1 += add.answer();
        }

        while ();
J. Steen
  • 15,470
  • 15
  • 56
  • 63
user1735367
  • 119
  • 1
  • 2
  • 6
  • What problem are you experiencing with that code? – deadly Oct 10 '12 at 15:31
  • Can you clarify why boxnumbers is even there and why you're attempted to add to an array using an unknown variable add with a method answer(). Also what is the value of list_box.Text – Dharun Oct 10 '12 at 15:32

2 Answers2

2

The magic of LINQ will save you, try .Sum()

Your code doesn't make much sense so I'll try to clear it up. I assume you have several rows of numbers in the list box like this.

1
5
3
6

Assuming you loaded it correctly as a list of ints, you get an sum of them using the following:

int sum = list_box.Items.Sum(i => (int)i.Value);

If you loaded it incorrectly as strings, then you need to parse it:

int sum = list_box.Items.Sum(i => int.Parse(i.Value));

You need to clarify your question a bit more if this doesn't solve your problem.

Dharun
  • 613
  • 8
  • 26
-1

A for loop might be better for you:

for(var i = 0; i < boxnumbers1.Count; i++)
{
     answer += boxnumbers1[i];
}
PiousVenom
  • 6,888
  • 11
  • 47
  • 86