|Make a GroupBox that uses a CheckBox in its caption to determine whether its items are enabled in Visual Basic .NET
|This example shows how to make a GroupBox that uses a CheckBox in its caption to determine whether its items are enabled in Visual Basic .NET
|GroupBox, CheckBox, enable, disable, Visual Basic .NET, VB.NET
At design time, set the GroupBox's Text property to an empty string and position a CheckBox so it looks like it is the GroupBox's caption. The result looks pretty good if you place the CheckBox inside the GroupBox and set its Location to 6, 0.
The CheckBox's Click event handler calls the ManageCheckGroupBox function, which does all of the interesting work.
Private Sub ManageCheckGroupBox(ByVal chk As CheckBox, _
ByVal grp As GroupBox)
If (grp.Parent Is Nothing) Then Exit Sub
If (grp.Parent.Controls Is Nothing) Then Exit Sub
' Make sure the CheckBox isn't in the GroupBox.
' This will only happen the first time.
If (chk.Parent Is grp) Then
' Reparent the CheckBox so it's not in the GroupBox.
' Adjust the CheckBox's location.
chk.Location = New Point( _
chk.Left + grp.Left, _
chk.Top + grp.Top)
' Move the CheckBox to the top of the stacking
' Enable or disable the GroupBox.
grp.Enabled = (chk.Checked)
' Get the appropriate color for the contained controls.
Dim fore_color As Color
If (grp.Enabled) Then
fore_color = _
fore_color = _
' Color the controls in the GroupBox.
For Each ctl As Control In grp.Controls
ctl.ForeColor = fore_color
Unfortunately if the CheckBox is inside the GroupBox, then when the CheckBox disables the GroupBox it also disables itself so the user won't be able to re-check the CheckBox. Complicating matters is the fact that the Form Designer tends to drop the CheckBox inside the GroupBox if you place the CheckBox over the GroupBox, so it's hard to arrange them nicely without putting one inside the other.
To handle this problem, the ManageCheckGroupBox function checks whether the CheckBox is inside the GroupBox and, if it is, the function moves it into the GroupBox's parent. It adjusts the CheckBox's location so it doesn't move on the screen and moves it to the front of the stacking order so it doesn't end up behind the GroupBox.
Next the code enables or disables the GroupBox (which enables or disables all of the controls it contains). It then gives the GroupBox's controls the proper color (normally black or gray) to indicate whether they are disabled.