Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Anchor property doesn't seem to work

I added some controls to my form and changed Anchor property how I'd expect this to work, but when I resize the form at the runtime, the controls stay at the same place.

For example, I have two buttons in bottom right corner of a form - they are on the form, no containers or anything like that. Anchor = Bottom, Right. FormBorderStyle = Sizable. But when I drag-resize the form while running, buttons do not move.

Am I missing something?

c# 2005

like image 556
flamey Avatar asked Oct 21 '09 10:10

flamey


2 Answers

Another possibility would be that you accidentally placed your buttons not directly on the form. Instead you put them in some container (eg. panel, tableLayoutPanel, etc) and this container doesn't have set its anchoring or docking values correct.

Just to be absolutely sure you should take a look into designer.cs and check if your buttons are added directly to the form by this.Controls.Add() function or if they are added in any other Controls-List (eg. panel.Controls.Add()).

like image 85
Oliver Avatar answered Nov 17 '22 10:11

Oliver


I know this an old post, but I'd like to try to contribute anyway.

My problem was that the form that I was adding into my panel didn't automatically adjust its size when the parent panel had its size changed.

The problem was that I was doing this:

form.WindowState = FormWindowState.Maximized; // <-- source of the problem
form.AutoSize = true; //this causes the form to grow only. Don't set it if you want to resize automatically using AnchorStyles, as I did below.
form.FormBorderStyle = FormBorderStyle.Sizable; //I think this is not necessary to solve the problem, but I have left it there just in case :-)
panel1.Controls.Add(form);
form.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                    | System.Windows.Forms.AnchorStyles.Left)
                    | System.Windows.Forms.AnchorStyles.Right)));
form.Dock = DockStyle.Fill; //this provides the initial size adjust to parent' size.
form.Visible = true;

To solve, I just commented the first line //form.WindowState = FormWindowState.Maximized; and everything worked like a charm.

like image 6
Roberto Avatar answered Nov 17 '22 10:11

Roberto