Niomi
Niomi

Reputation: 9

How to add numbers in a listBox

My program is supposed to generate 24 random numbers then add them all together and display them.

I've gotten them to do everything, except I can't get the first 24 numbers to add.
I tried moving the statement that collects the numbers but it didn't work.
Im not sure how to go forward.

int x = 0;
int number = 0;
int i = 0;

while (i < listBox1.Items.Count)
{
    number += Convert.ToInt32(listBox1.Items[i++]);
}

totaltextBox.Text = Convert.ToString(number);

Random ran = new Random();

for(x = 0;x <= 23; x++)
{
    listBox1.Items.Add(Convert.ToString(ran.Next(0,100)));
}
fileNumbers.Text = listBox1.Items.Count.ToString();

Upvotes: 0

Views: 5873

Answers (3)

Alexander Mills
Alexander Mills

Reputation: 277

As mentioned in the comments, you set your totaltextbox text too early. That way the listbox is empty when you try to accumulate the values.

Try this:

Random ran = new Random();

for (var x = 0; x <= 23; x++)
{
     listBox1.Items.Add(Convert.ToString(ran.Next(0, 100)));
}

var number = listBox1.Items.Cast<string>().Select(Int32.Parse).Sum();
var count = listBox1.Items.Count;

I also replaced your while loop with a LINQ-Expression. Also note, that in c# you can declare for-variables like in my example code. No need to declare them for the whole method (unless you want to use them after the for loop for whatever reason).

Upvotes: 1

nevra
nevra

Reputation: 428

Just replace for and while loop. if not, it cant take listBox1.Items.Count.

int x = 0;
int number = 0;
int i = 0;
Random ran = new Random();
for (x = 0; x <= 23; x++)
{
    listBox1.Items.Add(Convert.ToString(ran.Next(0, 100)));
}
while (i < listBox1.Items.Count)
{
    number += Convert.ToInt32(listBox1.Items[i++]);
}

totaltextBox.Text = Convert.ToString(number);
fileNumbers.Text = listBox1.Items.Count.ToString();

Upvotes: 1

Andrei Bucurei
Andrei Bucurei

Reputation: 2438

The other answers are correct. However I will add my solution which avoids some back and forth conversions and reduces iterations:

Random ran = new Random();
int total = 0;
for (int x = 0; x <= 23; x++)
{
 int rn = ran.Next(0, 100);
 total += rn;
 listBox1.Items.Add(rn.ToString());
}

totaltextBox.Text = total.ToString();

Upvotes: 0

Related Questions