30

How to make a panel center of form, even if the size of the form is changed. Using c# windows application

2
  • Do you want the panel to grow and shrink with the form? Or to retain it original size? Commented May 18, 2010 at 8:18
  • @Binary Worrier, It should in its original size. But should be center of the form depending on size of the form. Commented May 18, 2010 at 8:30

3 Answers 3

48

Position the panel in the center of the form using the designer, and then clear the Anchor property, so it is not anchored to any edge. This will keep it centered when the form resizes, without resizing the panel itself.

If, for some reason, you will need to position the panel in code (depending on things that happens during form load for instance) you can do something like this:

// code for initializing the panel and setting // its size goes here _thePanel.Location = new Point( this.ClientSize.Width / 2 - _thePanel.Size.Width / 2, this.ClientSize.Height / 2 - _thePanel.Size.Height / 2); _thePanel.Anchor = AnchorStyles.None; 

That should take care of most scenarios, I imagine.

Sign up to request clarification or add additional context in comments.

2 Comments

My panel has lot of controls in it. This application will run in many systems where the resolution varies. So, in that case the position of panel is different for different systems.
Excellent! I had no idea you could remove anchors entirely.
7

set its Anchor property to None :

this.panel1.Anchor = System.Windows.Forms.AnchorStyles.None; 

Comments

1
Private Sub Panel1_Paint(sender As Object, e As PaintEventArgs) Handles Panel1.Paint Panel1.Location = New Point(ClientSize.Width / 2 - Panel1.Size.Width / 2, ClientSize.Height / 2 - Panel1.Size.Height / 2) Panel1.Anchor = AnchorStyles.None End Sub 

1 Comment

Please note that code only answers are discouraged. Always provide a bit of explanation around it!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.