Search code examples
c#.netwinformssplitcontainer

Adjust form width to Match SplitContainer Size


I have a SplitContainer within a Form with the Dock property set to Fill .SplitPanel1 contains a picturebox,so when the picturebox size reduces,the right side of the form has blank space.

How can i trim the form size so that it matches its content?

I have tried

Myform.Size = Myform.splitContainer1.Size;

from the launching form.

But this is not working.What i'm i doing wrong?

UPDATE:

Screenshot

Design View

This is the Design View here you can see that the spiltpanel fills the form. There are 2 panels.The Left Panel contains a picturebox and Right Panel contains another panel.

enter image description here

RuntimeView

This is the runtime view.You can see that the picturebox size has reduced.I have set the splitcontainer to have borders and it occupies the full form

enter image description here

This is the code behind the Main form where i launch the form above

myform.endPointPictureBox1.Width = myform.splitContainer1.Panel1.Width/2;
myform.endPointPictureBox1.Height = myform.splitContainer1.Panel1.Height;
myform.endPointPictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

In the second form,i do the following the Load event

splitContainer1.SplitterDistance = endPointPictureBox1.Width;
splitContainer1.Width = endPointPictureBox1.Width + splitContainer1.Panel2.Width;
this.Width = splitContainer1.Width;

Solution

  • UPDATED 2

    Here is code that you need to do that:

    private void button1_Click(object sender, EventArgs e)
    {
        pictureBox1.Image = Image.FromFile(@"c:\Users\Admin\Desktop\tmp.png");
        if(splitContainer1.Orientation== Orientation.Vertical)
        {
            var prevWidthPanel2 = splitContainer1.Panel2.Width;
            splitContainer1.SplitterDistance = pictureBox1.Image.Width;
            this.Width = (this.Width - splitContainer1.Panel2.Width) + prevWidthPanel2;
            splitContainer1.SplitterDistance = pictureBox1.Width;
        }
    }
    

    I was doing this on button click, but I think there is no difference.
    The result of this is the following:

    Before click:

    enter image description here

    After click: enter image description here