views:

2114

answers:

3

I have items in a listbox control that I would like to repeatedly (when it gets to the last one, repeat) loop through and set the text to a label.

I'm stuck, please help!

A: 

Sounds like you need to be using eventing rather than polling in a loop. More details are needed.

Whyaduck
+1  A: 

Not sure what you are trying to achieve, but the following method will continuously cycle through the items of the given ListBox, displaying the values in the given Label control, going back from the start when it reaches the end, refreshing twice a second (C# code):

private int _currentIndex = -1;
private void ShowNextItem(ListBox listBox, Label label)
{
    // advance the current index one step, and reset it to 0 if it
    // is beyond the number of items in the list
    _currentIndex++;
    if (_currentIndex >= listBox.Items.Count)
    {
        _currentIndex = 0;
    }

    label.Text = listBox.Items[_currentIndex].ToString();

    // get a thread from the thread pool that waits around for a given
    // time and then calls this method again
    ThreadPool.QueueUserWorkItem((state) =>
    {
        Thread.Sleep(500);
        this.Invoke(new Action<ListBox, Label>(ShowNextItem), listBox, label);
    });
}

Call it like this:

ShowNextItem(myListBox, myLabel);
Fredrik Mörk
Fredrik, tack så mycket! :) Worked flawlessly!
Josh streit
You are welcome / ingen orsak :o)
Fredrik Mörk
A: 

Hi Fredrik Mörk,

I read your reply and it was great. Thanks a lot.

Sonny