group box

  • Thread starter Thread starter juli
  • Start date Start date
J

juli

Hello,

1)I wanted to know if there is a way to determine the size of a group
box according to the number of radio buttons being added to it?

2)Is there a way to access to the radio buttons (in code) via the
group box control?

Thank U veru much!
 
Hi Juli,

You can access any controls inside container controls like panels and
groupboxes.
Use the Controls property of the GroupBox to access its controls.

int n = 0;
foreach(Control c in MyGroupBox.Controls)
{
if(c is RadioButton)
n++;
}
MessageBox.Show("My GroupBox contains " + n + " RadioButtons.");

You can calculate the size based in the number of radiobuttons or access
the size of each control inside the GroupBox and add them together.

int h = 0;
int w = 0;
foreach(Control c in MyGroupBox.Controls)
{
if(c is RadioButton)
{
h += c.Size.Height;
w += c.Size.Width;
}
}

You can also set the Tag/Name property of the RadioButtons to identify
them further.
 
Hello,
I tried to do this:
foreach (Control c in this.groupBox1.Controls)
{
groupBox1.Size.Height=groupBox1.Size.Height+c.Height;
}

but I keep getting compile error:
Cannot modify the return value of 'System.Windows.Forms.Control.Size'
because it is not a variable

How can I change this value?

Another question,
My controls inside the group box are radio buttons and I need to know
which one of them been selected,how do I do it via the group box?

Thanks a lot!
 
Hi,

You can't set the height or width individually, you need to set the full
size property.

foreach (Control c in this.groupBox1.Controls)
{
groupBox1.Size = new Size(groupBox1.Size.Width, groupBox1.Size.Height
+ c.Height);
}

As for your second question, you need to cast the control back to a
radiobutton.

foreach (Control c in this.groupBox1.Controls)
{
RadioButton rb = (RadioButton)c;
if(rb.Checked)
// do stuff
}

Note that if you have other controls than radiobuttons you will get an
exception.
In that case, test for a radiobutton using if(c is RadioButton).
 
First of all ,Thanks! but I still have a problem with the size I did:
if(c is RadioButton)
{
groupBox2.Size = new Size(groupBox2.Size.Width,
groupBox2.Size.Height
+ c.Height);

}

but it becomes too huge ,maybe there need to be a casting or something ?
Thank you!
 
Without having tested it, I'm assuming the groupBox have an initial
default size that you need to ignore. Try setting the initial size to 0 or
perhaps even better, store the height of the RadioButtons only and set
GroupBox size at the end.


int n = 0;
foreach(Control c in groupBox2.Controls)
{
if(c is RadioButton)
n += c.Height;
}

groupBox2.Size = new Size(groupBox2.Size.Width, n);
 
Back
Top