P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

How can I get suspendlayout to work when adding controls?

I am adding controls after the shown event on Form. The controls are showing up one at a time despite the fact I called SuspendLayout(). How can I get the layout to suspend so the controls only display when they are all finished loading?

 public partial class ControlCreateTest : Form
{
    public ControlCreateTest()
    {
        InitializeComponent();       
    }

    private void AsyncControlCreateTest_Shown(object sender, EventArgs e)
    {
        CreateControls();
    } 

    private void CreateControls()
    {
        SuspendLayout();
        int startPoint= 0;            
        for (int i = 0; i < 4; i++)
        {          
            UserControl control = new UserControl() { Text = i.ToString(), Height = 100, Width = 100 };
            control.Load += control_Load;
            Controls.Add(control);
            control.Top = startPoint;
            startPoint += control.Height;
        }

        ResumeLayout();
        Text = "Loading complete";
    }

    void control_Load(object sender, EventArgs e)
    {
        Thread.Sleep(500);
        RichTextBox newRichTextBox = new RichTextBox() { Height = 100, Width = 100 };
        UserControl control = sender as UserControl;
        control.Controls.Add(newRichTextBox);
        newRichTextBox.Text = "loaded";
    }     
}

UPDATE
It seems that once these forms begin loading...the visibility and suspend calls are thrown out the window immediately. That is quite troublesome when the Load events are long running.

Upvotes: 1

Views: 2011

Answers (2)

P.Brian.Mackey
P.Brian.Mackey

Reputation: 44285

Getting a little hacked at the obscurity of Winforms dev. Anyway...I set the width and height of the form to 1 pixel in the constructor. When show is called I hide the window and put the window back to normal size. It's hard to notice the tiny window before it's hidden.

This lets my routines fire up and loading form display without all the headache.

UPDATE
When using ShowDialogue(), this dumb little trick only works if you Set Visible = true before Form_Shown returns control to the caller. I found that if you set Visible = true in Form.Shown the Closing event will be triggered...man I flipping love WINFORMS....

Upvotes: 1

Steve Wellens
Steve Wellens

Reputation: 20640

Try using AddRange to add all your controls at once:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.controlcollection.addrange.aspx

Upvotes: 0

Related Questions