Tutorial :how to resize the size of a control automatically when the size of the form changes



Question:

I am drawing a rectangle on my form and on top of that I have a label that I dragged. Now I want to re-size the rectangle that contains label so that it changes automatically when the size of the form is changed(maximized and all). I tried using

this.label1.Size = new Size();  

but this causes my label or may be rectangle to disappeared from the form. I cannot see it in my form now. Anchor and Dock properties do not serve my purpose. I have to hard code it. Need help on how to solve this resizing problem.


Solution:1

Use the .Anchor property.


Solution:2

Check out the Anchor and Dock properties. They should be able to provide you with the functionality that you need.

You could also look in to using the .SetBounds() method in the resize event.


Solution:3

You can either use Dock property of the control which allows you to make it align with the left, right, top or bottom edge of the form or fill the entire form.

Or use Anchor property, which allows you to anchor the coordinates - e.g. when you set anchor to left, right, top, bottom, it will resize with the form.


Solution:4

If Dock and Anchor are no good then just set the Width and Height properties. By creating a default Size object and assigning that to your control you are basically assigning Width and Height to 0.


Solution:5

You should handle the SizeChanged event:

this.SizeChanged += new EventHandler(Form1_SizeChanged);  

then in the envent handler method, you must arrange Size and Location of your control:

void Form1_SizeChanged(object sender, EventArgs e)  {     myControl.Size = new Size(w,h);  // size of the control     myControl.Location = new Point(x,y);  //coordinates from the upperleft corner of your control's container (the form in your case)  }  

N.B. AFAIK a label cannot be resized as you want (instead location is ok), because has a fixed size. Use textbox with Readonly and Multiline properties set to true


Solution:6

Try form Scale() method. But for me, it has a little strange behavior...


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »