0

Context is I am making a small app for our NBA fantasy draft using c# windows forms.

I am trying to make a button click set text to a label then wait before selecting the random item from the listbox. It seems that clicking the button doesn't do anything unless it is able to complete in its entirety. So Sleep doesn't work. Is there some way I can implement a delay between changing the label text and selecting the random item from the listbox and displaying it in the other listbox?

Hopefully that makes sense. Thanks in advance!

Here is my code:

private void button2_Click(object sender, EventArgs e)
        {
            string order;
            if (draftClicked == false && isLast == false)
            {
                order = "first";
                draftClicked = true;
            }
            else if (draftClicked == true && isLast == false)
            {
                order = "next";
                isLast = true;
            }
            else
            {
                order = "final";
            }
            
            label4.Text = "With the " + order + " pick in the 2022/23 \r\n Fantasy Season we have...";

            ListBox.ObjectCollection list = listBox1.Items;
            Random rng = new Random();

            int n = list.Count;

            if (n > 0)
            {
                int k = rng.Next(n);
                listBox2.Items.Add(list[k]);
                listBox1.Items.Remove(list[k]);
            }
        }
Matt
  • 75
  • 1
  • 3
  • 8
  • Have you used timers before? – Enigmativity Jul 05 '21 at 03:07
  • Easy way is to use `_ = Task.Delay(TimeSpan.FromSeconds(1)).ContinueWith(t => { some code })`. This continuation will be invoked on UI thread (if called from UI thread) and should be safe – JL0PD Jul 05 '21 at 03:15
  • 1
    Take a look at my answer to this question: https://stackoverflow.com/questions/68201663/c-sharp-string-iterator-for-showing-words-one-by-one/68202058#68202058. Not quite the same (it appends a new word to a text box every 200 ms), but pretty darn close. Get it working (it's a [mcve]), and then play with it to do what you want to do – Flydog57 Jul 05 '21 at 03:29
  • 2
    Old-school is to use `System.Windows.Forms.Timer`. Modern idiom uses `await Task.Delay(...);`. See duplicates for examples of both. – Peter Duniho Jul 05 '21 at 05:35

0 Answers0