Click here to Skip to main content
16,012,116 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
I am having a panel in winforms which loads panels in it during a method call. In the method call i have written following code:

C#
//to get number of panel present in main panel so that new panel position can be set
 int counT = panel1.Controls.Count;

 Panel p = new Panel();
 p.Location = new Point(3, 3 + (counT * 197));
 p.Size = new Size(280, 150);

 //To add panel to parent panel
 panel1.Controls.Add(p);


Every time I call the method it will load a panel in the main panel. Everything works fine if I didn't scroll bar. Once I scroll the Scroll bar to down and after that i call the method, the distance between panels increases.

As per logic written the distance between two panel should be 197 pixel along Y axis, but it is increasing by more.

I have set AutoScroll==true

Any help !!!
Posted
Updated 2-Nov-15 19:19pm
v2

C#
private void AddPanel(Panel target)
{
    int nControls = target.Controls.Count;

    Panel p = new Panel
    {
        Margin = new Padding(3),
        Anchor = AnchorStyles.Left | AnchorStyles.Top,
        Location = new Point(0, (nControls * 152)),
        Size = new Size(280, 150),
        BackColor = Color.AliceBlue,
        BorderStyle = BorderStyle.Fixed3D
    };

    target.Controls.Add(p);
}
If you want the Panels flush, then set their Dock property; example:

C#
private void AddDockedPanel(Panel target)
{
    int nControls = target.Controls.Count;

    Panel p = new Panel
    {
        Dock = DockStyle.Top,
        Size = new Size(280, 150),
        BackColor = Color.AliceBlue,
        BorderStyle = BorderStyle.Fixed3D
    };

    // verify you are getting added Panels
    // in the vertical order you expect
    // TextBox tb = new TextBox();
    // tb.Text = nControls.ToString();
    // p.Controls.Add(tb);

    target.Controls.Add(p);

    // fix the z-order so last Panel added is at the bottom
    p.BringToFront();
}
 
Share this answer
 
Comments
Digambar Malla 4-Nov-15 0:08am    
BillWoodruff, thanks for the solution...But later I find out FlowlayOutPanel control is the best alternative where it worked like charm for my requirement.
BillWoodruff 4-Nov-15 2:00am    
Hi Digambar, You're welcome, and I'm glad you found a solution.

In my experience, I found the TableLayoutPanel easier to work with than the FlowLayoutTable.
Try to set the Control.Anchor Property[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900