C # / winforms: How can two controls dynamically share available space?

How to configure my controls for the following situation:

I have a parent container like GroupBox .

Inside this parent container, I have two similar controls, such as ListBox es, next to each other. Both of them are the same size, so the border between them is exactly in the middle of the GroupBox .

Now that the GroupBox resized, I want the ListBox es to also be resized, but both should be the same size than the others. Thus, the border between them remains in the middle of the GroupBox .

So, how do I adjust the properties for these three controls to achieve the desired behavior?

+7
c # winforms
source share
3 answers

You need another container. TableLayoutPanel is the best solution. Use 1 row and 2 columns and a dock (Dock = Fill) in the group field. The width of both columns should be set to 50%. Then you can add your controls to individual cells and attach them (Dock = Fill)

+13
source share

Maybe a SplitContainer with two halves set evenly and IsSplitterFixed set to true (to stop it moving):

 [STAThread] static void Main() { Application.EnableVisualStyles(); Application.Run(new Form { Controls = { new SplitContainer { Width = 200, IsSplitterFixed = true, SplitterDistance = 100, SplitterWidth = 1, Dock = DockStyle.Fill, Panel1 = { Controls = { new ListBox { IntegralHeight = false, Dock = DockStyle.Fill, BackColor = Color.Blue, Items = {"abc","def","ghi"} } } }, Panel2 = { Controls = { new ListBox { Dock = DockStyle.Fill, BackColor = Color.Red, IntegralHeight = false, Items = {"jkl","mno","pqr"} } } } }} }); } 
+3
source share

It is also possible without a separator.

In the group dial resize event, set the location of the first control to {0,0} and the second to {GroupBox.Width / 2,0} and set the sizes of both to {GroupBox.Width / 2, GroupBox.Height}

You should also leave space around the controls so that they do not overlap with the GroupBox frame.

 private void groupBox1_Resize(object sender, EventArgs e) { groupBox1.SuspendLayout(); listBox1.Location = new Point(7, 20); listBox2.Location = new Point(groupBox1.Width / 2, 20); listBox1.Size = new Size(groupBox1.Width / 2 - 6, groupBox1.Height - 27); listBox2.Size = new Size((groupBox1.Width + 1) / 2 - 6, groupBox1.Height - 27); groupBox1.ResumeLayout(); } 
+1
source share

All Articles