6

I have two tab pages hosting TableLayoutPanels that I dynamically populate with labels and textboxes. The first one gets 96 labels and 96 textboxes, and its flicker is acceptable/tolerable, so I didn't bother to add a SuspendLayout/ResumeLayout pair.

However, the second one gets 96 labels and 288 textboxes, and its painting/flickering is intolerable. IOW, 192 controls seems to be okay, but 384 is decidedly not.

I was calling SuspendLayout prior to creating the controls dynamically, and then ResumeLayout in the finally block, but removed them, and voila! Like the first tabPage/TLP, the flicker is acceptable.

Why does this addition by subtraction work?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862

2 Answers2

10

You may also try the two methods, I have listed in this thread. Hope they are not too arcane:

https://stackoverflow.com/a/15020157/1307504

This methods really suspends and resumes the layout. But you should never forget to call EndControlUpdate().

I use this in any generically control I am creating. I tried a lot with alling suspend and resume layout. It never worked the way I thought it should.

Community
  • 1
  • 1
Patrick
  • 907
  • 9
  • 22
2

Initially, I had same doubt that does the SuspendLayout and ResumeLayout really works. Then I tried myself and created a sample application and got to know the concept much better later on.

So, here is what I did:

mainPanel.SuspendLayout()

create child control

call child.SuspendLayout()

change the child control properties

add the child control to the mainPanel

call child.ResumeLayout(false) - this means: next layout run, relayout this control, but not immediately

repeat (2-6) for every child-control

call mainPanel.ResumeLayout(true) - this means: relayout my mainPanel and every child-control now!

Also to Prove My Concept Here is the Sample Application

Stopwatch stopWatch = new Stopwatch();
        stopWatch.Start();

        this.SuspendLayout();
        for (int i = 0; i < 2000; i++)
        {
            var textbox = new TextBox();
            //textbox.SuspendLayout();
            //textbox.Dock = i% 2 ==0 ? DockStyle.Left : DockStyle.Right;
            textbox.Dock = DockStyle.Fill;
            textbox.Top = i * 10;
            textbox.Text = i.ToString();
            this.Controls.Add(textbox);
            //textbox.ResumeLayout(false);

        }
        stopWatch.Stop();
        TimeSpan ts = stopWatch.Elapsed;
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",ts.Hours, ts.Minutes, ts.Seconds,ts.Milliseconds / 10);

        this.ResumeLayout(true);
        MessageBox.Show(elapsedTime);
Gerry
  • 10,337
  • 3
  • 31
  • 40
Sandip
  • 252
  • 2
  • 13