0

So I'm trying to create a visualiser for sorting algorithms. Currently trying to get it to work with a simple insertion sort. The program generates a number of labels of 10 x (10 * ToSort[i]), which should be moved around after every step of said insertion sort.

So this method:

private void RefreshPanel()
    {
        for (int i = 0; i < toSort.Length; i++)
        {
            Label label = (Label)activePanel.Controls["lblVis" + toSort[i]];
            label.Top = ((10 * i) + i + 5);
        }
    }

gets called after every step in the sorting algorithm. While the labels do get moved, some of the labels lose their color until the algorithm is finished. In this attempt, the labels are identified by "lblVis" and the number the label represents.

Another attempt:

private void RefreshPanel()
    {
        LogArray();
        for (int i = 0; i < toSort.Length; i++)
        {
            activePanel.Controls["lblVis" + i].Width = 10 * toSort[i];
        }
    }

In this example the labels are again identified by "lblVis" + the amount of existing lblVis labels at time of creation. Then I try to change their width according to the value in the array that is being sorted.

Neither of these methods work however. Are labels just a bad Winform control to try to do this with? Or am I missing something very obvious?

Rayne
  • 1
  • 2
  • 1
    You are probably cross-threading, try invoking the new position on the UI thread. – Ron Beyer Oct 12 '15 at 18:21
  • Take a look [at this answer](http://stackoverflow.com/a/2568723/656243). – Lynn Crumbling Oct 12 '15 at 18:28
  • If you're not explicitly using multi-threaded code, then @NicoSchertler is almost certainly right. The "correct" way to do this would be to do the sorting on a background thread and marshall all the GUI updates to the GUI thread using `Invoke`, but that's hard and you may be able to get away with the `Application.DoEvents` hack suggested in the answer linked by @LynnCrumbling. – adv12 Oct 12 '15 at 18:31
  • The Application.DoEvents hack did nicely. Thanks for the help. – Rayne Oct 12 '15 at 18:33

0 Answers0