DockStyle Fill for RunTime Generated Controls

ImGreg picture ImGreg · Mar 6, 2012 · Viewed 14.1k times · Source

I'm trying to do something very simple that is giving me huge problems in C# Winforms. I have two group boxes on a TabPage. One docked right and one docked bottom. I also have a Chart on the page (System.Windows.Forms.DataVisualization.Charting). This Chart is to Dock.Fill the remaining space on the page.

I first encountered the problem of the chart hiding behind both group boxes and still dock filling the entire page. However, I found I could solve this by using "BringToFront" (or reordering the Document Outline order) and then the Chart docked properly and didn't overlap any other controls on the page.

However, I am trying to add a Chart to the page at runtime and it again fills the entire page and hides behind the other controls. How can I go about making this work?

EDIT: Forgot to mention, calling "BringToFront" will throw an exception "Width must be greater than 0px".

chart_TapChart = new Chart();
chart_TapChart.Dock = DockStyle.Fill;
chart_TapChart.BringToFront();
GroupBox gp1 = new GroupBox();
gp1.Dock = DockStyle.Right;
GroupBox gp2 = new GroupBox();
gp2.Dock = DockStyle.Bottom;
this.Controls.Add(chart_TapChart);    <--this refers to tabpage
this.Controls.Add(gp1);
this.Controls.Add(gp2);

Answer

ImGreg picture ImGreg · Mar 6, 2012

Turns out, you have to wait until the TabPage has been viewed already (you have to programatically call yourtabpage.select()), then search through the controls on that tabpage, find the chart, and call "BringToFront" on it. You may have the Dock.Fill set before adding the control to the page.

You cannot setup its z-index until the tabpage is rendered.