I am trying to dynamically create Windows controls and add them to a Panel. For Button and Checkbox this has worked fine; I\'ve run into a problem with a GroupBox, though, with
If you set a breakpoint, you'll see that your groupbox contains all the radiobuttons. Their location is indeed all the same, so they're displayed one above the other. The problem is not adding them all to the groupbox, but displaying them all.
To achieve that, simply increment their location on each add operation to display them all :
private GroupBox getGroupBox(string currentSettings, int curLeftVal)
{
// "apple~orange~peach~True (must look for "enclose group in a black box" as the last val (ignore for the quick-and-dirty mockup, though))
List grpbxVals = new List(currentSettings.Split('~'));
GroupBox gb = new GroupBox();
gb.Height = 60;
gb.Location = new Point(curLeftVal, PANEL_TOP_LOC);
RadioButton radbtn = null;
// "-1" because we're ignoring the final bool ("enclose in black box")
int radButtonPosition = PANEL_TOP_LOC;
for (int i = 0; i < grpbxVals.Count - 1; i++)
{
radbtn = new RadioButton();
radbtn.Text = grpbxVals[i];
radbtn.Location = new Point(curLeftVal, radButtonPosition );
radButtonPosition += radbtn.Height;
gb.Controls.Add(radbtn);
}
return gb;
}
I'm defining a variable called radButtonPosition
and initializing it to your groupbox's position. I'm then setting the radiobutton location according to it and then simply incrementing that radButtonPosition
by the height of a radiobutton each time one is added.
Here's also a little refactored version :
private GroupBox CreateGroupboxWithRadiobuttons(string currentSettings, int curLeftVal)
{
IList grpbxVals = new List(currentSettings.Split('~'));
GroupBox gb = new GroupBox { Height = 60, Location = new Point(curLeftVal, PANEL_TOP_LOC) };
int radButtonPosition = PANEL_TOP_LOC;
for (int i = 0; i < grpbxVals.Count() - 1; i++)
{
gb.Controls.Add(new RadioButton {Text = grpbxVals[i], Location = new Point(curLeftVal, radButtonPosition)});
radButtonPosition += new RadioButton().Height;
}
return gb;
}
There's of course a LOT of method extraction to do to respect SRP, but that's a start.