user3036459
user3036459

Reputation:

How to choose when to loop through listbox?

I have a listbox of items that I want to go through one by one and each item should be printed in a messagebox. I want to by default, when it reaches the end of the listbox, to just stop. But if I check my checkbox "Loop through list [x]" I want it to continue and just start over when it reaches the bottom. How can I do that?

This is my code right now to loop through it.

int i = 0;
i = listBox1.SelectedIndex;
i = i + 1;
if (i > listBox1.Items.Count - 1)
i = 0;
listBox1.SelectedIndex = i;
MessageBox.Show("Item: " + listBox1.SelectedItem.ToString());

This never ends though, it just continues to loop. How can I make a check that if it's on the bottom it just stops? This should be my code if I checked the box "Loop through list [x]"...

This is all in my Timer1 with Interval 5000ms

edit: Also, how can I make it print like "You have reached the end of the list!" when it comes to the bottom of the listbox?

Upvotes: 1

Views: 154

Answers (1)

BradleyDotNET
BradleyDotNET

Reputation: 61369

You said that is all in "Timer1", which means the code actually looks like:

private void TimerElapsed(...)
{
    int i = 0;
    i = listBox1.SelectedIndex;
    i = i + 1;
    if (i > listBox1.Items.Count - 1)
    i = 0;
    listBox1.SelectedIndex = i;
    MessageBox.Show("Item: " + listBox1.SelectedItem.ToString());
}

When you reach the end, you set i = 0, which just allows the loop to continue without throwing. To stop the loop, you need to stop the timer invoking this function as well.

The correct code would be:

private void TimerElapsed(...)
{
    int i = 0;
    i = listBox1.SelectedIndex;
    i++;
    if (i > listBox1.Items.Count - 1)
    {
       MessageBox.Show("End of list reached!");
       if (LoopAfterEnd)
          i = 0;
       else
          Timer1.Stop();
    }
    listBox1.SelectedIndex = i;
    MessageBox.Show("Item: " + listBox1.SelectedItem.ToString());
}

It could also be written:

private void TimerElapsed(...)
{
    int i = 0;
    i = listBox1.SelectedIndex;
    i++;
    if (i > listBox1.Items.Count - 1)
    {
       MessageBox.Show("End of list reached!");
       i = 0;
       if (!LoopAfterEnd)
          Timer1.Stop();
    }
    listBox1.SelectedIndex = i;
    MessageBox.Show("Item: " + listBox1.SelectedItem.ToString());
}

Which has the advantage of letting you restart the loop later by just starting the timer again!

Upvotes: 1

Related Questions